1.快速排序:是對冒泡排序的一種改進,其基本思想是選取一個記錄作爲樞軸,經過一趟排序,將整段序列劃分爲兩個部分,其中一部分的值都小於樞軸,另一部分都大於樞軸,然後繼續對這兩部分進行排序,從而使整個序列達到有序。
1)我們從待排序的記錄序列中選取一個記錄(通常第一個)作爲基準元素(稱爲key)key=arr[left],然後設置兩個變量,left指向數列的最左部,right指向數據的最右部。
2) key首先與arr[right]進行比較,如果arr[right]<key,則arr[left]=arr[right]將這個比key小的數放到左邊去,如果arr[right]>key則我們只需要將right--,right--之後,再拿arr[right]與key進行比較,直到arr[right]<key交換元素爲止。
(3) 如果右邊存在arr[right]<key的情況,將arr[left]=arr[right],接下來,將轉向left端,拿arr[left ]與key進行比較,如果arr[left]>key,則將arr[right]=arr[left],如果arr[left]<key,則只需要將left++,然後再進行arr[left]與key的比較。
(4) 然後再移動right重複上述步驟
(5) 最後得到 {18 11 0 8} 23 {46},再對左子數列與右子數列進行同樣的操作。最終得到一個有序的數列。
//快速排序:
#include<stdio.h>
//遞歸實現:
void quicksort(int *arr, int low, int high)
{
int i, j, m, tmp;
tmp = arr[low];
if (low < high)
{
//Swap(s[l], s[(l + r) / 2]); //將中間的這個數和第一個數交換 參見注1
int i = low, j = high, x = arr[low];
while (i < j)
{
while (i < j && arr[j] >= x) // 從右向左找第一個小於x的數
j--;
if (i < j)
arr[i++] = arr[j];
while (i < j && arr[i] < x) // 從左向右找第一個大於等於x的數
i++;
if (i < j)
arr[j--] = arr[i];
}
arr[i] = tmp;
quicksort(arr, low, i - 1); // 遞歸調用
quicksort(arr, i + 1, high);
}
}
int main()
{
int arr[] = { 2, 5, 6, 8, 12, 7, 16, 11 };
int len = sizeof(arr) / sizeof(int);
quicksort(arr,0,7);
for (int i = 0; i < len; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
//非遞歸
//劃分算法
int Partition(int a[], int low, int high)
{
//假設每次都以第一個元素作爲樞軸值,進行一趟劃分:
int pivot = a[low];
while (low<high)
{
while (low<high && a[high] >= pivot)
--high;
a[low] = a[high]; //停下來做交換
while (low<high && a[low] <= pivot)
++low;
a[high] = a[low]; //停下來做交換
}
a[low] = pivot; //pivot的最終落點
return low;
}
void QuickSort(int a[], int left, int right)
{
//手動利用棧來存儲每次分塊快排的起始點
//棧非空時循環獲取中軸入棧
stack<int> s;
if (left < right)
{
int boundary = Partition(a, left, right);
if (boundary - 1 > left) //確保左分區存在
{
//將左分區端點入棧
s.push(left);
s.push(boundary - 1);
}
if (boundary + 1 < right) //確保右分區存在
{
s.push(boundary + 1);
s.push(right);
}
while (!s.empty())
{
//得到某分區的左右邊界
int r = s.top();
s.pop();
int l = s.top();
s.pop();
boundary = Partition(a, l, r);
if (boundary - 1 > l) //確保左分區存在
{
//將左分區端點入棧
s.push(l);
s.push(boundary - 1);
}
if (boundary + 1 < r) //確保右分區存在
{
s.push(boundary + 1);
s.push(r);
}
}
}
}
int main()
{
int arr[] = { 2, 5, 6, 8, 12, 7, 16, 11 };
int len = sizeof(arr) / sizeof(int);
QuickSort(arr,0,7);
for (int i = 0; i < len; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
歸併排序: