#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
void insert_sort(int a[],int n){
int h,i,j,temp;
for(h=n/2; h>0; h/=2) {
for (i = h; i < n; i+=h) {
temp = a[i];
for (j = i - h; a[j] > a[j + h] && j >= 0; j-=h)
swap(a[j], a[j + h]);
a[j+h]=temp;
}
}
}
void bubble_sort(int a[],int len){
int i= 0, j = 0 , exchange = 0 ;
for(i=1 ; i < len ; i++){
for(j = 0 ; j < len-i ; ++j )
{
if(a[j+1] < a[j]){
swap(a[j],a[j+1]);
exchange=1;
}
}
if( exchange != 1 ) return;
}
}
void quick_sort(int a[],int low,int high){
int i,j,pivot;
if(low < high)
{
pivot = a[low];
i=low , j = high;
while( i < j ){
while(i<j && a[j]>=pivot) j--;
if(i<j) a[i++]=a[j];
while(i<j && a[i]<= pivot) i++;
if(i < j) a[j--] = a[i];
}
a[i]=pivot;
quick_sort(a,low,i-1);
quick_sort(a,i+1,high);
}
}
void select_sort(int a[], int len) {
int i, j, min, temp;
for(i=0; i < len-1 ; ++i)
{
min = i;
for(j=i+1; j < len; ++j)
if(a[min] > a[j])
min=j;
swap(a[min],a[i]);
}
}
int heapSize= 0;
int Left(int index){ return ( (index<<1)+1 ); }
int Right(int index){ return ((index << 1)+2) ; }
void max_heapify(int arr[], int start, int end) {
//建立父節點指標和子節點指標
int dad = start;
int son = dad * 2 + 1;
while (son <= end) { //若子節點指標在範圍內才做比較
if (son + 1 <= end && arr[son] < arr[son + 1]) //先比較兩個子節點大小,選擇最大的
son++;
if (arr[dad] > arr[son]) //如果父節點大於子節點代表調整完畢,直接跳出函數
return;
else { //否則交換父子內容再繼續子節點和孫節點比較
swap(arr[dad], arr[son]);
dad = son;
son = dad * 2 + 1;
}
}
}
void heap_sort(int arr[], int len) {
//初始化,i從最後一個父節點開始調整
for (int i = len / 2 - 1; i >= 0; i--)
max_heapify(arr, i, len - 1);
//先將第一個元素和已经排好的元素前一位做交換,再從新調整(刚调整的元素之前的元素),直到排序完畢
for (int i = len - 1; i > 0; i--) {
swap(arr[0], arr[i]);
max_heapify(arr, 0, i - 1);
}
}
int main(int argc ,char** argv)
{
int a[]={7,30,5,2,51,4,6};
//insert_sort(a,7);
//bubble_sort(a,7);
//quick_sort(a,0,7);
//select_sort(a,7);
heap_sort(a,7);
for (int i = 0; i < 7 ; ++i) {
cout<<a[i]<<" "<<endl;
}
cout<<2500<<endl;
return 0;
}
各大排序算法
最新推荐文章于 2023-06-29 09:22:49 发布