## CSDN博客

### C++ 排序算法

#include <iostream.h>
void SelectSort(int arr[], int len)
{
for (int i=0; i<len-1; i++)
{
int min = i;
for (int j=i+1; j<len; j++)
{
if (arr[j] < arr[min])
{
min = j;
}
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}

void InsertSort(int arr[], int len)
{
for (int i=1; i<len; i++)
{
int tmp = arr[i];
for (int j=i-1; j>=0 && tmp<arr[j]; j--)
{
arr[j+1] = arr[j];
}
arr[j+1] = tmp;
}
}

void BubbleSort(int arr[], int len)
{
for (int i=len-1; i>0; i--)
{
bool exchanged = false;
for (int j=0; j<i; j++)
{
if (arr[j] > arr[j+1])
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
exchanged = true;
}
}
if (!exchanged)
{
return;
}
}
}

void QuickSort(int arr[], int i, int j)
{
int low = i;
int high = j;
if (low < high)
{
int pivot = arr[low];
do
{
while (high>low && arr[high] >= pivot)
{
high--;
}
if (high > low)
{
arr[low] = arr[high];
}
while (low < high && arr[low] <= pivot)
{
low++;
}
if (low < high)
{
arr[high] = arr[low];
}
} while(low < high);
arr[low] = pivot;
for (int ii=0; ii<8; ii++)
{
cout<<arr[ii]<<'/t';
}
cout<<endl;
QuickSort(arr, i, low-1);
QuickSort(arr, low+1, j);
}
}

void main()
{
int ii;
int arr[] = {4,5,6,3,8,9,5,1};
int len = sizeof(arr) / sizeof(arr[0]);
//    SelectSort(arr, len);
//    InsertSort(arr, len);
//    BubbleSort(arr, len);
QuickSort(arr, 0, len-1);
for (ii=0; ii<len; ii++)
cout<<arr[ii]<<'/t';
cout<<endl<<endl;
}

0 0