演算法基礎2 快排 堆排 桶排

2021-09-23 22:33:37 字數 1949 閱讀 4587

// 整理於左神的演算法課

一。快排(荷蘭國旗問題)(時間複雜度o(n*logn),額外空間複雜度o(logn))

給定乙個陣列arr,和乙個數num,請把小於num的數放在陣列的

左邊,等於num的數放在陣列的中間,大於num的數放在陣列的右邊。

要求額外空間複雜度o(1),時間複雜度o(n)

快排的實現:

public static void quicksort(int arr) 

quicksort(arr, 0, arr.length - 1);

}public static void quicksort(int arr, int l, int r)

}public static int partition(int arr, int l, int r) else if (arr[l] > arr[r]) else

} swap(arr, more, r);

return new int ;

}public static void swap(int arr, int i, int j)

二。堆排序 (時間複雜度o(n*logn),額外空間複雜度o(1))

詳細:思路:

a.將無需序列構建成乙個堆,根據公升序降序需求選擇大頂堆或小頂堆;

b.將堆頂元素與末尾元素交換,將最大元素"沉"到陣列末端;

c.重新調整結構,使其滿足堆定義,然後繼續交換堆頂元素與當前末尾元素,反覆執行調整+交換步驟,直到整個序列有序

注意

1,堆結構的heapinsert與heapify

2,堆結構的增大和減少

3,如果只是建立堆的過程,時間複雜度為o(n)

4,優先順序佇列結構,就是堆結構

public static void heapsort(int arr) 

for (int i = 0; i < arr.length; i++)

int size = arr.length;

swap(arr, 0, --size);

while (size > 0)

}public static void heapinsert(int arr, int index)

}public static void heapify(int arr, int index, int size)

swap(arr, largest, index);

index = largest;

left = index * 2 + 1; }}

public static void swap(int arr, int i, int j)

三。桶排序

桶排序、計數排序、基數排序的介紹

1,非基於比較的排序,與被排序的樣本的實際資料狀況很有關係,所

以實際中並不經常使用

2,時間複雜度o(n),額外空間複雜度o(n)

3,穩定的排序

// only for 0~200 value

public static void bucketsort(int arr)

int max = integer.min_value;

for (int i = 0; i < arr.length; i++)

int bucket = new int[max + 1];

for (int i = 0; i < arr.length; i++)

int i = 0;

for (int j = 0; j < bucket.length; j++)

}}

四。排序的穩定性

1.概念:

排完序之後相對序列不變

2.工程中應用的排序演算法

基本資料型別(資料多) :快排

其他(資料多):歸併

(資料少):插排

2011 4 15 快排演算法,堆排演算法

template int get pivot index value type array,int start,int end value type pivot array start while start end while startpivot end array start array en...

快排和堆排

一 快速排序 最常用的排序演算法,速度通常也是最快的。時間複雜度 o nlogn 最壞 o n 2 空間複雜度 o nlgn 不穩定 比如 5 3 3 4 3 8 9 10 11 這個序列,在中樞元素5和3交換就會把元素3的穩定性打亂 實現原理 快排主要是通過選擇乙個關鍵值作為基準值。比基準值小的都...

快排 歸併 堆排

快排 include include include includeusing namespace std void quicksort vector a,int l,int r 終止遞迴的條件,子串行長度為1 int mid low high low 2 取得序列中間的元素 mergesort a...