Steps for bubble sort:
- Start at the end of the array with the outer loop and count backwards till the start of the array.
- Have an inner loop start at the start of the array and count forward till it reaches the index of the outerloop from step 1.
- Within the inner loop if you meet any two elements (j & j+1) that are not sorted....sort them!
#includeint main(void) { int list[] = { 3, 4, 1, 10, 23, 40, 2, 9}; int arr_length = sizeof(list)/sizeof(list[0]); for(int i = arr_length-1; i >= 0; --i){ for(int j = 0; j < i; ++j) { if(list[j] > list[j+1]) { int temp = list[j]; list[j] = list[j+1]; list[j+1] = temp; } } } for( int i = 0; i < arr_length; ++i) { printf("%d ", list[i]); } printf("\n"); }
No comments:
Post a Comment