首页 > 代码库 > 快速排序的实现(c语言)
快速排序的实现(c语言)
以前写的代码
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | // // main.c // cTest // // Created by Zizhu on 13-10-8. // Copyright (c) 2013年 Zizhu. All rights reserved. // #include <stdio.h> #define N (10) void quickSor( int *nums, int indexStart, int indexEnd); int partition( int *nums, int indexStart, int indexEnd); void exchange( int *nums, int p1, int p2); void printNums( int *nums, int count); int main() { printf ( ">>>strat\n" ); int nums[N] = {0, 4, 2, 5, 1, 3, -1, 19, 99, -100}; printNums(nums, N); int mid = partition(nums, 0, N-1); printNums(nums, N); printf ( "mid = %d\n" , mid); quickSor(nums, 0, N-1); printNums(nums, N); return 0; } void quickSor( int *nums, int indexStart, int indexEnd) { if (indexEnd > indexStart) { int indexMid = partition(nums, indexStart, indexEnd); quickSor(nums, indexStart, indexMid-1); quickSor(nums, indexMid+1, indexEnd); } } int partition( int *nums, int indexStart, int indexEnd) { int p2 = indexStart-1; int p1; int target = nums[indexEnd]; for (p1 = indexStart; p1 < indexEnd; p1++) { if (nums[p1] <= target) { p2++; exchange(nums, p1, p2); } } exchange(nums, p2+1, indexEnd); return p2+1; } void exchange( int *nums, int p1, int p2) { int tmp = nums[p1]; nums[p1] = nums[p2]; nums[p2] = tmp; } void printNums( int *nums, int count) { printf ( "numbers : " ); int i; for (i = 0; i < count; ++i) { printf ( "%4d\t" , nums[i]); } printf ( "\n" ); } |
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。