Quick sorting and binarysearch)
Address: http://blog.csdn.net/caroline_wendy
Quick sorting and Binary SearchThis article mainly explains how to write these two classical algorithms.
The two algorithms that programmers must master are required to use paper in any language.
Fast sorting (c ):
/** Main. CPP ** created on: September 10, 2014 * 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 ;}
Binary Search (c ):
/** Main. CPP ** created on: September 10, 2014 * 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; elsereturn 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 ;}
Programming algorithms-quick sorting and binarysearch)