推排序演算法C C

2021-07-06 10:19:18 字數 1203 閱讀 3266

在堆排序演算法中,我們使用的是最大堆。下面的**是給定一組數,構造乙個最大堆。left(heap, location)和right(heap, location)分別返回陣列heap中location的左右孩子的索引。max_heapify(heap, i)是確保heap陣列的i的左右孩子都滿足最大堆化。bulid_max_heap(heap)將heap陣列構造乙個最大堆。heapsort(heap)是對heap最大堆進行排序。

/*

構造乙個num個數最大堆;

*/#include#includeusing namespace std;

const int num = 10;

int heapnum = num;

void print(int p , int n)

}int left(int heap , int i)

int right(int heap , int i)

void max_heapify(int heap, int location)

else

largest = location;

if (r <= heapnum && heap[r] > heap[largest])

if (location != largest) }

void bulid_max_heap(int heap)

}void heapsort(int heap)

}int main()

; srand(time(null));

for (int i = 1; i <= num; i++)

cout << "-------------random number is: " << endl;

print(heap, num);

bulid_max_heap(heap);

cout << "-------------max heap is: " << endl;

print(heap, num);

heapsort(heap);

cout << "-------------sort number is: " << endl;

print(heap, num);

return 0;

}

結果如下:

排序演算法c c

include void bubble sort1 int array,int arraysize int main void bubble sort1 array,5 排序好後為 1 2 3 4 5 int i for i 0 i 5 i printf d array i puts 以前做排序為了...

C C 演算法 快速排序

氣泡排序的執行效率太低,因為每次比較相鄰的兩個數,所以時間複雜度為o n 花費的時間太長,所以為了更加的節省時間,提高程式的執行速率,我們可以採用快速排序。對於乙個數集,先把第乙個數當作基準數,然後分別從最右端和最左端向另一方向進行搜尋,以從小到大的順序為例 從右向左搜尋的,遇到比基準數小的與從左向...

C C 演算法 基礎排序

選擇排序 selectionsort 插入排序 insertsort 氣泡排序類似於汽水的氣泡一樣,從杯子底部一直公升到杯子的頂部,在上公升過程中氣泡會逐漸變大,這一過程類似於讓一組資料從小到大排列。從第乙個元素開始,與當前元素的相鄰元素進行比較,如果兩個元素之間逆序則交換,保證在比較完成後一組資料...