分别用插入排序,希尔排序,基数排序排序1-6数字(c++)
时间: 2024-02-20 15:56:49 浏览: 80
六种排序(c++)
好的,以下是三种排序算法的实现(C++代码):
1. 插入排序
```cpp
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;
}
}
```
2. 希尔排序
```cpp
void shellSort(int arr[], int n) {
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
}
arr[j] = temp;
}
}
}
```
3. 基数排序
```cpp
void radixSort(int arr[], int n) {
int maxElement = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > maxElement) {
maxElement = arr[i];
}
}
for (int exp = 1; maxElement / exp > 0; exp *= 10) {
int output[n];
int count[10] = {0};
for (int i = 0; i < n; i++) {
count[(arr[i] / exp) % 10]++;
}
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
for (int i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
}
```
这三个算法分别对数组 {1, 2, 3, 4, 5, 6} 进行排序的结果如下:
- 插入排序:{1, 2, 3, 4, 5, 6}
- 希尔排序:{1, 2, 3, 4, 5, 6}
- 基数排序:{1, 2, 3, 4, 5, 6}
阅读全文