Thursday, February 10, 2011

Bubble Sort

 a sorting algorithm in which item is swap in the adjacent item until the list of item will be sorted just like bubble(in ascending order),the smaller item will slowly moved to the top and the larger item will slowly moved to the bottom.

Algorithm:
Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them.
If at least one swap has been done, repeat step 1.

Pseudocode(C++):

void bubbleSort(int arr[], int n) {
      bool swapped = true;
      int j = 0;
      int tmp;
      while (swapped) {
            swapped = false;
            j++;
            for (int i = 0; i < n - j; i++) {
                  if (arr[i] > arr[i + 1]) {
                        tmp = arr[i];
                        arr[i] = arr[i + 1];
                        arr[i + 1] = tmp;
                        swapped = true;
                  }
            }
      }
}

Source:
http://en.wikipedia.org/wiki/Bubble_sort
http://www.algolist.net/Algorithms/Sorting/Bubble_sort

No comments:

Post a Comment