冒泡
void BubbleSort(int arr[],int len)
{
if(arr == NULL)
{
cout<<"arr is null"<<endl;
return;
}
if(len < 2)
{
cout<<"the array len is 1"<<endl;
}
for(int i = 0; i<len; i++)
{
for(int j=0; j<len-i-1; j++)
{
if(arr[j]>=arr[j+1])
{
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
}
快速
void QuickSort(int array[], int low, int high)
{
int i = low;
int j = high;
cout<<"low:"<<low<<",high:"<<high<<endl;
if(i >= j) {
return;
}
int temp = array[low];
while(i != j)
{
while(array[j] >= temp && i < j)
{
j--;
}
while(array[i] <= temp && i < j)
{
i++;
}
if(i < j) {
cout<<"swap:"<<array[i]<<","<<array[j]<<endl;
swap(array[i], array[j]);
}
}
//array[i]=temp;
//将基准temp放于自己的位置,(第i个位置)
swap(array[low], array[i]);
for(int i = 0;i<5;i++)
{
cout<<array[i]<<endl;
}
QuickSort(array, low, i - 1);
QuickSort(array, i + 1, high);
}
插入
void InsertSort(int arr[], int len)
{
if(arr == NULL)
{
cout<<"arr is null"<<endl;
return;
}
if(len < 2)
{
cout<<"the array len is 1"<<endl;
}
for(int i=1; i<len; i++)
{
for(int j=i-1; j>=0; j--)
{
if(arr[j]>arr[j+1])
{
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
else
{
break;
}
}
}
}
选择
void SelectSort(int arr[],int len)
{
if(arr == NULL)
{
cout<<"arr is null"<<endl;
return;
}
if(len < 2)
{
cout<<"the array len is 1"<<endl;
}
for(int i = 0; i<len; i++)
{
int mindex = i;
for(int j=i; j<len-1; j++)
{
if(arr[mindex]>=arr[j+1])
{
mindex = j+1;
}
}
cout<<"current min index"<<mindex<<endl;
if(mindex != i)
{
int tmp = arr[mindex];
arr[mindex] = arr[i];
arr[i] = tmp;
}
}
}