C++ Array Sorting Methods
There are multiple sorting methods for arrays in C++, here are some common ones:
- Bubble Sort: By comparing adjacent elements and continuously swapping positions, the larger values gradually “bubble” towards the end of the array.
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
- Selection Sort: Each time, the algorithm finds the smallest (or largest) element from the unsorted portion and swaps it with the first element of the unsorted portion.
void selectionSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
int minIndex = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
- Insertion Sort: Dividing the array into a sorted portion and an unsorted portion, each time inserting the first element of the unsorted portion into the correct position of the sorted portion.
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
}
- Quick Sort: Select a pivot element, partition the array into two subarrays with elements on the left less than or equal to the pivot and elements on the right greater than the pivot, recursively apply quick sort to the subarrays.
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j <= high-1; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i + 1;
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi-1);
quickSort(arr, pi+1, high);
}
}
These are just some common sorting algorithms, and there are implementations of other sorting algorithms in C++. Choosing the appropriate sorting algorithm based on the actual situation and needs can both improve sorting efficiency and reduce resource consumption.