Monday, September 30, 2013

Sorting algorithm refreshers...Bubble Sort!

So it's been awhile since I did my sorting algorithms. It's funny how sophmore/junior year computer science can trip me up if I haven't thought about it in awhile. Anyway the next few posts will be for future reference. They are all in C and I'll start with the root of all evil Bubble Sort and it's very very bad O(n^2) growth rate!

Steps for bubble sort:
  1. Start at the end of the array with the outer loop and count backwards till the start of the array.
  2. 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.
  3. Within the inner loop if you meet any two elements (j & j+1) that are not sorted....sort them!

#include

int 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