From Clomosy Docs
Bubble sort is one of the simplest sorting algorithms. In this comparison-based algorithm, each element in the list is compared with the element next to it.
If the value of the first element is greater than the value of the second element, the two elements are swapped.
Then, the values of the second and third elements are compared. If the value of the second element is greater than the value of the third element, these two elements are swapped, and this process continues until the entire list is sorted.
Steps:
- Start at the beginning of the list and compare the first two adjacent items.
- If they are in the wrong order, swap them.
- Repeat this process for each pair of adjacent items until you reach the end of the list.
- After reaching the end of the list, exclude the last item from the next pass and repeat the process.
- Continue this process until the entire list is sorted.
Example
var arr: array[0..6] of Integer; i,j,n,temp : Integer; str : string; void bubbleSort; { n = Length(arr); for (i = 0 to n - 2) { for (j = 0 to n - i - 2) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } { arr[0] = 12; arr[1] = 11; arr[2] = 13; arr[3] = 5; arr[4] = 1; arr[5] = 7; arr[6] = 9; str = 'Unordered array: '; for (i = 0 to Length(arr)-1) { str = str + IntToStr(arr[i]) + ' '; } ShowMessage(str); bubbleSort; str = 'Array sorted from smallest to largest: '; for (i = 0 to Length(arr)-1) { str = str + IntToStr(arr[i]) + ' '; } ShowMessage(str); str = 'Array sorted from largest to smallest: '; for (i = Length(arr)-1 downto 0) { str = str + IntToStr(arr[i]) + ' '; } ShowMessage(str); }