Bubble Sort Method is one of the sorting methods which is the simple sorting algorithm that runs by repeatedly swapping the adjacent elements if they are in the wrong order. Bubble sort sometimes referred to as sinking sort.
You can use this bubble_sort() function to sort an integer array in its range as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
void bubble_sort(int A[], int n) { for ( int i = 0; i < n-1; i++ ) for ( int j = 0; j < n-i-1; j++ ) if (A[j] > A[j+1]) { auto temp = A[j]; A[j] = A[j+1]; A[j+1] = temp; } } |
In C++ Builder sorting text string lines is very easy by setting the Sorted property of a StringList to true. The example below sorts a given text file and saves it as a sorted in the same name. Let’s use this bubble_sort() function in an example.
1. Create a new C++ Builder Console project, Save all unit and project files into a folder. modify lines as below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#pragma hdrstop #pragma argsused #ifdef _WIN32 #include <tchar.h> #else typedef char _TCHAR; #define _tmain main #endif #include <stdio.h> void bubble_sort(int A[], int n) { for ( int i = 0; i < n-1; i++ ) for ( int j = 0; j < n-i-1; j++ ) if (A[j] > A[j+1]) { auto temp = A[j]; A[j] = A[j+1]; A[j+1] = temp; } } int _tmain(int argc, _TCHAR* argv[]) { int numbers[] = { 7, 85, 1, 48, 3 }; for(int i=0; i<5; i++) printf("%d,", numbers[i]); bubble_sort(numbers, 5); printf("\nSorted as\n"); for(int i=0; i<5; i++) printf("%d,", numbers[i]); getchar(); return 0; } |
2. Hit F9 or press Run button in C++ Builder to run your code.