Preview

Sorting Algorithms

Powerful Essays
Open Document
Open Document
3316 Words
Grammar
Grammar
Plagiarism
Plagiarism
Writing
Writing
Score
Score
Sorting Algorithms
THE THREE ELEMENTARY SORTING ALGORITHMS

Bubble Sort
Bubble Sort is probably one of the oldest, easiest, straight-forward, and inefficient sorting algorithms. It is the algorithm introduced as a sorting routine in most introductory courses on Algorithms. Bubble Sort works by comparing each element of the list with the element next to it and swapping them if required. With each pass, the largest of the list is "bubbled" to the end of the list whereas the smaller values sink to the bottom. It is similar to selection sort although not as straight forward. Instead of "selecting" maximum values, they are bubbled to a part of the list.
Code:
#define max n /*where n is the array size.*/ void BubbleSort(int a[])
{
int i, j, temp; for (i = 0; i < (max - 1); ++i) { for (j = 0; j < max - 1 - i; ++j ) { if (a[j] > a[j+1]) { temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; } } }
}
Key Terms:
Bubble Step - is the step in which the largest element is bubbled to its correct position. Bubble step is handled by the inner for loop.

for (j = 0; j < max - 1 - i; ++j )
{
if (a[j] > a[j+1]) { temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; }
}

Explanation:
The first for loop: for (i = 0; i < (max - 1); ++i)
----------------------------------------------------
‘i’ is used as a counter for the number times we are going to swap, and that since we have (max-1) elements, we can only swap less than (max-1) times.
The ‘Bubble Step’: for (j = 0; j < max - 1 - i; j++)
{
if (a[j] > a[j+1]) { temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; }
}
--------------------------------------------------------- ‘j’ is used as an index traversal of the array.

You May Also Find These Documents Helpful