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;
}
这些都是常用的数组排序方法,具体使用哪种方法取决于实际需求和性能要求。