zoukankan      html  css  js  c++  java
  • Algorithm Gossip (37) 快速排序法 ( 一 )

    前言

    This Series aritcles are all based on the book 《经典算法大全》; 对于该书的所有案例进行一个探究和拓展,并且用python和C++进行实现; 目的是熟悉常用算法过程中的技巧和逻辑拓展。

    提出问题

    37.Algorithm Gossip:快速排序法 ( 一 )

    讲述

    开始到重要的算法了, 快速排序的复杂度是 O(n*log(n)); 精髓在于减少了很多没必要的比较, 所以性能上来了; 快排1 是最基础的快排, 就是把前面k个排好, 第k+1 个元素依次和前面的比较进行插入。

    关于快速排序和归并排序可以在我的博客中搜索, 有详细讲解, 一年前我刚学Java时候, 把这些算法都进行了一个尝试, 并且有总结。

    分析和解释

    代码

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #define MAX 10
    #define SWAP(x,y) {int t; t = x; x = y; y = t;}
    void quicksort(int[],int,int);
    int main(void) {
    	int number[MAX] = {0};
    	int i, num;
    	srand(time(NULL));
    	printf("排序前:");
    	for(i = 0; i < MAX;i++){
    		number[i] = rand()% 100;
    		printf("%d ", number[i]);
    		}
    	quicksort(number, 0, MAX-1);
    	printf("
    排序后:");
    	for(i = 0; i < MAX;i++)
    		printf("%d ", number[i]);
    	printf("
    ");
    	return 0;
    	}
    void quicksort(int number[], int left, int right){
    	int i, j, s;
    	if(left < right){
    		s = number[left];
    		i = left;
    		j = right + 1;
    		while(1){
    			// 向右找
    			while(i + 1 < number.length && number[++i] < s) ;
    			// 向左找
    			while(j -1 > -1 && number[--j] > s) ;
    			if(i >= j)
    				break;
    			SWAP(number[i],number[j]);
    			}
    		number[left] = number[j];
    		number[j] = s;
    		quicksort(number,left,j-1); // 对左边进行递回
    		quicksort(number,j+1,right); // 对右边进行递回
    		}
    	}
    

    拓展和关联

    后记

    参考书籍

    • 《经典算法大全》
    • 维基百科
  • 相关阅读:
    my first android test
    VVVVVVVVVV
    my first android test
    my first android test
    my first android test
    ini文件
    ZZZZ
    Standard Exception Classes in Python 1.5
    Python Module of the Week Python Module of the Week
    my first android test
  • 原文地址:https://www.cnblogs.com/actanble/p/6711119.html
Copyright © 2011-2022 走看看