[置顶] 各种排序算法

快速排序:

void Qsort(int a[], int low, int high){
	if(low >= high)
		return;
	int first = low, last = high;
	int key = a[first];
	while(first < last){
		while(first < last && a[last] >= key)
			--last;
		a[first] = a[last];
		while(first < last && a[first] <= key)
			++first;
		a[last] = a[first];
	}
	a[first] = key;
	Qsort(a, low, first - 1);
	Qsort(a, first + 1, high);
}


冒泡排序

void bubbleSort(int a[], int n){
	for(int i = 0; i < n; ++i){
		for(int j = 0; j < n - i - 1; ++j){
			if(a[j] > a[j+1]){
				int temp = a[j];
				a[j] = a[j + 1];
				a[j + 1] = temp;
			}
		}
	}
}



选择排序

void selectSort(int a[], int n){
	for(int i = 0; i < n; ++i){
		int k = i;
		for(int j = i + 1; j < n; ++j){
			if(a[j] < a[k])
				k = j;
		}
		if(k != i){
			int temp = a[k];
			a[k] = a[i];
			a[i] = temp;
		}
	}
}



堆排序

#include <stdio.h>

void heapAdjust(int *array, int i, int nLength){
	int nChild;
	for(; 2 * i + 1 < nLength; i = nChild){
		nChild = 2 * i + 1;
		if(nChild < nLength - 1 && array[nChild + 1] > array[nChild])
			++nChild;
		if(array[i] < array[nChild]){
			int nTemp = array[i];
			array[i] = array[nChild];
			array[nChild] = nTemp;
		}
		else
			break;
	}
}

void heapSort(int *array, int length){
	for(int i = length / 2 - 1; i >= 0; --i)
		heapAdjust(array, i, length);
	for(int i = length - 1; i > 0; --i){
		int nTemp = array[i];
		array[i] = array[0];
		array[0] = nTemp;
		heapAdjust(array, 0, i);
	}
}

int main(){
	int num[] = {9, 8, 6, 3, 7, 4, 2, 0, 1, 5};
	heapSort(num, sizeof(num) / sizeof(int));
	for(int i = 0; i < sizeof(num) / sizeof(int); ++i)
		printf("%d ", num[i]);
	return 0;
}





归并排序

void merge(int a[], int low, int mid, int high){
	int i = low, j = mid + 1, k = low;
	int b[1000];
	while(i <= mid && j <= high){
		if(a[i] <= a[j])
			b[k++] = a[i++];
		else
			b[k++] = a[j++];
	}
	while(i <= mid)
		b[k++] = a[i++];
	while(j <= high)
		b[k++] = a[j++];
	for(int i = low; i <= high; ++i)
		a[i] = b[i];
}

void mergeSort(int a[], int low, int high){
	if(low < high){
		int mid = (low + high) / 2;
		mergeSort(a, low, mid);
		mergeSort(a, mid + 1, high);
		merge(a, low, mid, high);
	}
}


二分查找:

int binarySearch(int *a, int length, int key){
	if(a == NULL || length <= 0)
		return -1;
	int low = 0, high = length - 1;
	while(low <= high){
		int mid = (low + high) / 2;
		if(a[mid] == key)
			return mid;
		else if(a[mid] < key)
			low = mid + 1;
		else 
			high = mid - 1;
	}
	return -1;
}


你可能感兴趣的:([置顶] 各种排序算法)