快速排序(QuickSort)和二分查找(BinarySearch)
本文地址: http://blog.csdn.net/caroline_wendy
快速排序和二分查找的定义, 网上书上都有, 本文主要是讲解如何写出这两个经典算法.
程序员必须掌握的两种算法, 使用任何语言, 使用纸都是必须的.
快速排序(C):
/* * main.cpp * * Created on: 2014年9月10日 * Author: Spike */ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <exception> int RandomInRange(int start, int end) { int res = rand()%(end-start+1) + start; return res; } void Swap(int* num1, int* num2) { int tmp = *num1; *num1 = *num2; *num2 = tmp; } int Partition(int data[], int length, int start, int end) { if (data == NULL || length <= 0 || start > end || start < 0 || end >= length) { return -1; } int index = RandomInRange(start, end); Swap(&data[index], &data[end]); int small = start-1; for (index = start; index < end; ++index) { if (data[index] < data[end]) { small++; if (small != index) Swap(&data[index], &data[small]); } } small++; Swap(&data[small], &data[end]); return small; } void QuickSort(int data[], int length, int start, int end) { if (start == end) return; int index = Partition(data, length, start, end); if (index > start) QuickSort(data, length, start, index-1); if (index < end) QuickSort(data, length, index+1, end); } int main(void) { int data[] = {1, 4, 5, 2, 3, 7, 8, 6}; int length = 8; QuickSort(data, length, 0, length-1); for (int i=0; i<length; ++i) { printf("%d ", data[i]); } printf("\n"); return 0; }
二分查找(C):
/* * main.cpp * * Created on: 2014年9月10日 * Author: Spike */ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <exception> int BinarySearch(int data[], int length, int value) { int left = 0; int right = length-1; while (left <= right) { int middle = left + (right-left); if (data[middle] > value) right = middle - 1; else if (data[middle] < value) left = middle + 1; else return middle; } return -1; } int main(void) { int data[] = {1, 2, 3, 4, 5, 6, 7, 8}; int length = 8; printf("%d ", BinarySearch(data, length, 5)); printf("\n"); return 0; }
时间: 2024-10-29 04:27:21