//冒泡
#include
using namespace std;
void bubbleSort(int* list,int index)
{
for(int i=index;i>0;i--) //index 最大的那个索引
{
for(int j=0;j)
{
if(list[j]>list[j+1])
{
int temp;
temp=list[j];
list[j]=list[j+1];
list[j+1]=temp;
}
}
}
}
void main()
{
int list[9]={3,4,1,5,2,8,7,9,6};
for(int i=0;i<9;i++)
cout<" | ";
cout<<endl;
bubbleSort(list,8);//index:= 9-1
for(int i=0;i<9;i++)
cout<" | ";
}
//插入排序法
#include
using namespace std;
void insertSort(int* list,int index)
{
//在排序之前我们需要搞清一个思路,新插入一个数据的时候,排序过后的数组都是
//从小到大排列好的,所以我们需要从后往前查找,直到找到比我们要插入的数字还小的
//值。这个时候我们需要一个变量j作为标识
//从1开始
for(int i=1;i<=index;i++) //index 最大的那个索引
{
int insertNode=list[i];
int j;
for(j=i-1;j>=0;j--)
{
if(insertNode<list[j])
list[j+1]=list[j];
else
break; //因为前面的已经排序好,所以找到位置后 就可以退出了
}
list[j+1]=insertNode;
}
}
void main()
{
int list[9]={3,4,1,5,2,8,7,9,6};
for(int i=0;i<9;i++)
cout<" | ";
cout<<endl;
insertSort(list,8);//index:= 9-1
for(int i=0;i<9;i++)
cout<" | ";
}
//选择排序法
#include
using namespace std;
void selectSort(int* list,int index)
{
for(int i=0;i<=index;i++) //index 最大的那个索引
{
int minValue=list[i];
int minIndex=i;
for(int j=i;j<=index;j++)
{
if(minValue>list[j])
{
minValue=list[j];
minIndex=j;
}
}
int temp;
temp=list[i];
list[i]=list[minIndex];
list[minIndex]=temp;
}
}
void main()
{
int list[9]={3,4,1,5,2,8,7,9,6};
for(int i=0;i<9;i++)
cout<" | ";
cout<<endl;
selectSort(list,8);//index:= 9-1
for(int i=0;i<9;i++)
cout<" | ";
}
//快速排序法
#include
using namespace std;
int Partition(int a[], int low, int high)
{
int x = a[high];//将输入数组的最后一个数作为主元,用它来对数组进行划分
int i = low - 1;//i是最后一个小于主元的数的下标
for (int j = low; j < high; j++)//遍历下标由low到high-1的数
{
if (a[j] < x)//如果数小于主元的话就将i向前挪动一个位置,并且交换j和i所分别指向的数
{
int temp;
i++;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
//经历上面的循环之后下标为从low到i(包括i)的数就均为小于x的数了,现在将主元和i+1位置上面的数进行交换
a[high] = a[i + 1];
a[i + 1] = x;
return i + 1;
}
void QuickSort(int a[], int low, int high)
{
if (low < high)
{
int q = Partition(a, low, high);
QuickSort(a, low, q - 1);
QuickSort(a, q + 1, high);
}
}
void main(){ int arry[] = {3,4,1,5,2,8,7,9,6};
for (int i = 0; i < 9; i++)
{
cout << arry[i] <<" | ";
}
cout<<endl;
QuickSort(arry, 0, 8);
for (int i = 0; i < 9; i++)
{
cout << arry[i] <<" | ";
}
}