Dr. Sajib Datta Feb 14, 2014
Ordering elements in some way For numeric data, ascending order is the most common Lots of techniques for sorting These techniques vary in performance both with runtime and usage of extra memory
Given a sequence of numbers, it compares adjacent numbers and swap them if necessary Repeats the above procedure until all numbers are in right place
Pick 4, compare with 10
Pick 10, compare with 9 Need to swap
Pick 10, compare with 6 Need to swap
Pick 10, compare with -1
Notice, that 10 is at the right position Now, repeat from the beginning
Compare 1 st element with 2 nd element
Compare 2nd element with 3rd element Swap needed
Compare 3 rd element with 4 th element Swap needed
Now, do we need the compare 4 th with the 5 th ? We already know 5 th element is the largest. This implies, what we have as the 4 th element, it must be the second largest, and is already in the correct place.
Now, repeat from the beginning again. But remember, we only need to go up to 3 rd this time.
1 st iteration places the largest number in the correct place 2 nd iteration places the second largest number in the correct place ….. …. i-th iteration places the i-th largest number in the correct place
#include #define ARR_SIZE 8 int main(void) { int intarr[ARR_SIZE] = {23, 4, 12, 8, 22, 1, 54, 9}, i, j, tmp; for(i = 0; i<ARR_SIZE-1; i++) { for(j = 0; j<ARR_SIZE-i-1; j++) { if(intarr[j]>intarr[j+1]) { tmp = intarr[j]; intarr[j] = intarr[j+1]; intarr[j+1] = tmp; } } } printf("The array sorted by Bubble Sort: "); for(i = 0; i< ARR_SIZE; i++) printf("%d ", intarr[i]); return 0; }