C++數組從小到大排序的方法有多種,以下是常用的幾種方法:
sort
函數來對數組進行排序。sort
函數位于<algorithm>
頭文件中。例如:#include <iostream>
#include <algorithm>
int main() {
int arr[] = {5, 2, 9, 1, 3};
int size = sizeof(arr) / sizeof(arr[0]);
std::sort(arr, arr + size);
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
#include <iostream>
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {5, 2, 9, 1, 3};
int size = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, size);
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
#include <iostream>
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);
}
}
int main() {
int arr[] = {5, 2, 9, 1, 3};
int size = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, size - 1);
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
這些都是常用的數組排序方法,具體使用哪種方法取決于實際需求和性能要求。