Wednesday, May 22, 2013

Self explaining bubble sort code in c.

#include
#include
void getData(void);
void bubbleSort(int [],int);
void printArray(int [],int);

int main(){
getData();
}

void getData(){
int* Array;
int Size,index;

printf("\n How many numbers you would like to sort?");
scanf("%d",&Size);
Array = (int *)malloc(Size*sizeof(int));
for(index=0; index < Size; index++){
printf("\n Enter number %d:",(index+1));
scanf("%d",&Array[index]);
}
printf("\n Array entered is:");
printArray(Array,Size);
bubbleSort(Array,Size);
}

void bubbleSort(int Array[],int Size){
int index1,index2,temp,count=0;

for(index1=0;index1<=Size;index1++){
for(index2=index1+1;index2<=Size-1;index2++){
printf("\n Comparing %d with %d.",Array[index1],Array[index2]);
count++;
_sleep(1000);
if(Array[index1]>Array[index2]){
printf("\n Number %d is greater than %d.",Array[index1],Array[index2]);
printf("\n Swapping elements %d and %d",Array[index1],Array[index2]);
_sleep(1000);
temp = Array[index1];
Array[index1]=Array[index2];
Array[index2]=temp;
printf("\n Array elements after modification are:");
printArray(Array,Size);
}
else if(Array[index1]==Array[index2]){
printf("\n Number are equal");
}
else{
printf("\n Number %d is less than %d.",Array[index1],Array[index2]);
}
}
}
printf("\n Total compares : %d \n\n\n",count);
}

void printArray(int Array[],int Size){
int index;

for(index=0; index < Size; index++){
printf("\t %d",Array[index]);
}
printf("\n\n\n");
}

No comments:

Post a Comment