I'm beginning with c++, I'm writing a program to sort array with int data type, with swap function as follows:
void swap(int *a, int *b){
int m;
m = *a;
*a = *b;
*b = m;
}
I know when calling swap function we have to pass parameter to it as an address (ex: swap(&a[i], &a[j]) but if I try passing parameter as a value (ex : swap(a[i], a[j]), swap function is working properly, I'm a bit confused about this, an explanation would help me a lot, many thanks
Sorry, I edited, here is my full source code
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<conio.h>
using namespace std;
void swap(int *a, int *b){
int m;
m = *a;
*a = *b;
*b = m;
}
void bubblesort(int * a, int n){
for (int i = 0; i < n - 1; i++){
for (int j = i + 1; j < n; j++){
if (a[i] <= a[j]) swap(a[i], a[j]);
}
}
}
int main(){
int aray[6] = {2,4,6,1,9,7};
bubblesort(aray, 6);
for (int i = 0; i < 6; i++)
{
cout << aray[i];
}
_getch();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire