zoukankan      html  css  js  c++  java
  • 高速排序

    高速排序

    原理

        和之前学习到的归并排序一样。高速排序也使用了分治的思想。

    如果现有一个数组a[start,end],对这个数组进行高速排序分了以下三个步骤:

    1. 分解:在数组a[start,end]中确定一个标准(通常是找a[end]),以这个标准调整元素并找出一个位置p,使得start<=i<=p-1区域内的全部元素都小于等于a[end],而p+1<=i<=end这个区域中全部元素都大于等于a[end]。以下是图解:
      这里写图片描写叙述
    2. 解决:通过递归调用高速排序,对分出来的子数组a[start,p-1]和a[p+1,end]进行排序。
    3. 合并:由于子数组都是原址排序的,因此不须要合并的操作。

    C语言实现

    int partition(int* a, int start, int end)
    {
        int x = a[end];
        int i = start;
        //调整整个数组中元素的位置并找出中间值的索引
        for (int j = start; j < end; j++)
        {
            if (a[j] <= x)
            {
                int t = a[i];
                a[i] = a[j];
                a[j] = t;
                i++;
            }
        }
        //将中间值放在找出的中间值索引处
        int t = a[i];
        a[i] = a[end];
        a[end] = t;
        return i;
    }
    
    void quick_sort(int* a, int from, int to)
    {
        if (from < to)
        {
            int p = partition(a, from, to);
            quick_sort(a, from, p - 1);
            quick_sort(a, p + 1, to);
        }
    }
    
    void main()
    {
        int count, *p;
        printf("请输入须要排序的数的个数 :");
        scanf_s("%d", &count);
        p = (int*)malloc(count * 2);
        printf("
    请输入须要排序的%d个数字:",count);
        for (int i = 0; i < count; i++)
        {
            scanf_s("%d", p+i);
        }
        printf("
    高速排序后的数组:");
    
        quick_sort(p, 0, count - 1);
        for (int i = 0; i < count; i++)
        {
            printf("%d ", p[i]);
        }
        printf("
    ");
        system("pause");
    }
    

    算法分析

        

  • 相关阅读:
    9、Spring Boot 2.x 集成 Thymeleaf
    【专题】Spring Boot 2.x 面试题
    8、Spring Boot 2.x 服务器部署
    7、Spring Boot 2.x 集成 Redis
    6、Spring Boot 2.x 集成 MyBatis
    5、Spring Boot 2.x 启动原理解析
    4、Spring Boot 2.x 自动配置原理
    3、Spring Boot 2.x 核心技术
    2、Spring Boot 2.x 快速入门
    centOS下安装JDK1.8.60,glassfish4.1.1以及MySQL
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/6973322.html
Copyright © 2011-2022 走看看