- 专题二 简单排序算法
- 阅读代码,回答下列问题:
- #include <iostream>
- using namespace std;
- const int M = 100;
- const int N = 10;
- int T[N+1];//桶排序专用数组(元素值为0-N的整数)
- void PrintArray(const int A[], int low, int high); //输出数组A中区域[low,high]的元素
- void BubbleSort (int A[], int n); //用冒泡排序法对数组A进行排序(非递减序列)
- void SelectionSort(int A[], int n); //用选择排序法对数组A进行排序(非递减序列)
- void InsertSort(int A[], int n); //用插入排序法对数组A进行排序(非递减序列)
- void BucketSort(int A[], int n);//用桶排序法对数组A进行排序(非递减序列)
- int main()
- {
- int A[M] = {2,8,2,1,2,6,5,6};
- int B[M] = {2,8,2,1,2,6,5,6};
- int C[M] = {2,8,2,1,2,6,5,6};
- int D[M] = {2,8,2,1,2,6,5,6};
- int n = 8;
- BubbleSort(A, n);//冒泡排序算法
- PrintArray(A, 0, n-1);
- SelectionSort(B, n);//选择排序算法
- PrintArray(B, 0, n-1);
- InsertSort(C, n);//插入排序算法
- PrintArray(C, 0, n-1);
- BucketSort(D, n);//桶排序算法
- PrintArray(D, 0, n-1);
- return 0;
- }
- void PrintArray(const int A[], int low, int high) //输出数组A中区域[low,high]的元素
- {
- while (low <= high)
- cout << A[low++] << " ";
- cout << endl;
- }
- 算法1:用冒泡排序法对数组A进行排序(非递减序列)
- void BubbleSort(int A[], int n)
- {
- int temp;
- for (int i=n-1; i>0; i--)
- {
- for (int j=0; j<i; j++) //通过交换相邻位置元素,进行冒泡操作
- {
- if (A[j] > A[j+1])
- {
- temp = A[j];
- A[j] = A[j+1];
- A[j+1] = temp;
- }
- }
- }
数组专题讲义之简单排序算法
最新推荐文章于 2022-05-30 11:25:12 发布