Last active
August 29, 2015 14:23
-
-
Save SohanChy/1ded92277da25b3e943a to your computer and use it in GitHub Desktop.
BubbleSort for array In C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
void fprintArray(int arrayi[], int arrayLength); | |
int main() | |
{ | |
//counters to use in all loops | |
int i,j; | |
//make an array | |
int arrayLength = 15; | |
int myArray[arrayLength]; | |
for(i=0;i<arrayLength;i++) | |
{ | |
myArray[i]= (rand()%30)+1; | |
} | |
//print generated array | |
fprintArray(myArray, arrayLength); | |
//sort the array | |
/* | |
Bubble sort | |
//Small number bubbles up to end. and this done one by one for all members results in sorted array. | |
// First thing to do. | |
Check first element with next, swap if second>first. | |
check second with next, swap if third>second. | |
... ... ... | |
*/ | |
//this loop runs the comparison for all elements | |
for(j=0;j<arrayLength;j++) //run whatever is inside arrayLength times. | |
{ | |
//this loop does the compare and swap | |
for(i=0;i<(arrayLength-1)-j;i++) //when comparing next guy is considered by +1, so loop should run length -1. | |
// -j means that the last j guys are already sorted, no need to compare. | |
{ | |
if(myArray[i]>myArray[i+1]) //compare to next guy and if next guy is bigger, swap. | |
{ | |
int temp; | |
temp = myArray[i+1]; | |
myArray[i+1] = myArray[i]; | |
myArray[i] = temp; | |
} | |
} | |
} | |
//print sorted array | |
fprintArray(myArray, arrayLength); | |
return 0; | |
} | |
//Function printArray | |
void fprintArray(int arrayi[],int arrayLength) | |
{ | |
int i; | |
for(i=0;i<arrayLength;i++) | |
{ | |
printf(" %d",arrayi[i]); | |
} | |
printf("\n"); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment