实现几种常用的排序方法,后续补充:
#include<iostream>
using namespace std;
//1.BubbleSort
int* BubbleSort(int array[],int const N)
{
int *Arr = new int[N];
for (int i = 0; i < N; i++)
{
Arr[i] = array[i];
}
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;
}
}
return Arr;
}
//2.selection sort
int* SelectSort(int array[], int const N)
{
int *Arr = new int[N];
for (int i = 0; i < N; i++)
{
Arr[i] = array[i];
}
for (int i = 0; i < N - 1; i++)
{
int tp = i;
for (int j = i + 1; j < N; j++)
if (Arr[tp]>Arr[j])
{
tp = j;
}
int temp = Arr[i];
Arr[i] = Arr[tp];
Arr[tp] = temp;
}
return Arr;
}
void Traverse(int array[],int N)
{
for (int i = 0; i < N ;i++)
cout << array[i] << ',';
}
//3.InsertSort
int* InsertSort(int array[], int const N)
{
int *Arr = new int[N];
for (int i = 0; i < N; i++)
{
Arr[i] = array[i];
}
//从右往左进行比较,假设某段序列已经排序好,将此序列右边的元素以此和该段序列进行比较,并将比较过的序列往右移动
for (int i = 1; i < N ; i++)
{
int tp = i-1;//排好序列段落的前一个数值
int get = Arr[i];//待比较值
while (tp >= 0 && get<Arr[tp])//比较段落每个数值与待比较数值的大小
{
Arr[tp+1] = Arr[tp];//移动数值
tp--;
}
Arr[tp + 1] = get;
}
return Arr;
}
//5.QuickSort
void quickSort(int s[], int l, int r)
{
if (l< r)
{
int i = l, j = r, x = s[l];
while (i < j)
{
while(i < j && s[j]>= x) // 从右向左找第一个小于x的数
j--;
if(i < j)
s[i++] = s[j];
while(i < j && s[i]< x) // 从左向右找第一个大于等于x的数
i++;
if(i < j)
s[j--] = s[i];
}
s[i] = x;
quickSort(s, l, i - 1); // 递归调用
quickSort(s, i + 1, r);
}
}
---------------------
//4.ShellSort
//6.MergeSort
int main()
{
int const N = 7;
int array[N] = {2, 5, 4, 6, 8, 1, 7};
cout << "Original:";
Traverse(array, N);
cout << endl;
int *Bubble = BubbleSort(array, N);
cout << "Bubble:" << endl;
Traverse(Bubble, N);cout << endl;
int *Selection = SelectSort(array, N);
cout << "Selection:" << endl;
Traverse(Selection, N); cout << endl;
int *Insertion = InsertSort(array, N);
cout << "Insertion:" << endl;
Traverse(Insertion, N); cout << endl;
system("pause");
return 0;
}