排序演算法總結 持續更新

2021-09-24 09:35:35 字數 2686 閱讀 6364

1.選擇排序法

//1.選擇排序 o(n2) 穩定

template void selectionsort(t arr, int n)

swap(arr[i], arr[minindex]);

}}

2.插入排序法

//2 插入排序 o(n2) 穩定,,近乎有序的陣列時,效率很高

// 1.交換法 使用swap, 效率較低

template void insertionsort1(t arr, int n)

}}// 2.賦值法 效率相對較高

template void insertionsort2(t arr, int n)

arr[j] = e;

}}// 3.其他排序呼叫版

template void insertionsort(t arr, int l, int r)

arr[j] = e;

}}

3.歸併排序

//3 歸併排序法 時間複雜度o(nlogn) 空間複雜度o(n) 穩定排序方法

// 1.自頂向下

template void mergesort(t arr, int n)

template void __mergesort(t arr, int l, int r)

template void __merge(t arr, int l, int mid, int r)

else if(j > r)

else if(aux[i-l] < aux[j-l])

else

}

}// 2.自底向上

template void mergesortbu(t arr, int n)

4.快速排序

//4 快速排序法 平均時間複雜度o(nlogn) 空間複雜度o(1) 不穩定

// 1.單路排序

template void quicksort1(t arr, int n)

template void __quicksort1(t arr, int l, int r)

template void __partition1(t arr, int l, int r)

}swap(arr[l], arr[j]);

return j;

}// 2.雙路排序

template void quicksort2(t arr, int n)

template void quicksort2(t arr, int l, int r)

template void __partition2(t arr, int l, int r)

if(j >= l && arr[j] > v)

if(i > j)

break;

swap(arr[i], arr[j]);

i++;

j--;

}swap(arr[l], arr[j]);

return j;

}// 3.三路快排

template void quicksort3(t arr, int n)

template void __quicksort3(t arr, int l, int r)

else if(arr[i] > v)

else

i++;

}swap(arr[l], arr[lt]);

__quicksort3(arr, l, lt-1);

__quicksort3(arr, gt, r);

}

5.堆排序

//5 堆排序 o(nlogn)

// 1.先手寫個最大堆 索引從1開始

template class maxheap

//heapify 最大非葉子節點索引號為 n/2

maxheap(t arr, int n)

count = n;

for(int k = count/2; k > 0; k--)

}int size()

bool isempty()

void insert(t& e)

t extractmax()

private:

void shiftup(int k)

}void shiftdown(int k)

}private:

t *data;

int capacity;

int count;

};

// 2.堆排序 需要建立額外的堆空間

template void heapsort1(t arr, int n)

}// 3.原地堆排序 索引從0開始

template void heapsort(t arr, int n)

for(int i = n-1; i >0; i--)

}template void shiftdown(t arr, int n, int k)

}

6.二分查詢法

//6 二分查詢法

int binarysearch(int arr, int n, int target)

return -1;

}

排序演算法總結(持續更新)

基本思想 通過對待 排序序列從前向後 從下標較小的元素開始 依次比較 相鄰元素的值,若發現逆序則交換,使值較大 的元素逐漸從前移向後部,就象水底下的氣泡一樣逐漸 向上冒。規則 實現 未優化 public static void bubblesort int arr 時間複雜度 空間複雜度 優化氣泡排...

排序演算法大總結(持續更新。。。)

主要思路 選擇乙個基準數字 一般是第乙個數字 設定兩個指標分別為 i和j,j從序列後面往前跳動,i從序列前面往後跳動,j遇到乙個比基準數字小的數字那麼停止,i遇到乙個比基準數字大的數字停止,如果i和j不相等,那麼將這兩個數字交換,直到i和j相等,終止迴圈,將第i個數字和選擇的基準數字交換位置,那麼操...

常用排序演算法總結。 力求持續更新

歸併排序是將兩個或者兩個以上的有序序列進行合併的一種排序演算法。採用了分治的思想。一般使用遞迴。最好 最壞 平均時間複雜度都是o nlgn 由於在歸併過程中需要與原始記錄序列同樣數量的儲存空間存放歸併結果以及遞迴深度為lg2n的棧空間,因此 空間 複雜度為o n logn include inclu...