zoukankan      html  css  js  c++  java
  • 基于快速排序,寻找众数(出现最多的数),运用分治的思想

    // ConsoleApplication4.cpp: 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include<iostream>
    using namespace std;

    #include<iostream>
    using namespace std;

    void middl(int &p, int &q, int &r)//找枢轴,然后把枢轴位置都换到第一位,左中右,取中值,放在左边第一个
    {
    if (p > q) swap(p, q);
    if (p > r) swap(p, r);
    if (q > r) swap(q, r);
    swap(p, q);
    }

    int quicksort(int *a, int L, int R,int max)//和枢轴相同的数可以和枢轴放一起来缩小下次快排的规模
    {

    if (L < R)
    {
    int mid = (L + R) / 2;
    middl(a[L], a[mid], a[R]);
    int count1 = L, count2 = R;
    int i = L;
    int j = R;
    int key = a[L];

    while (i < j)//一趟快排的总控制
    {
    while (i < j && a[j] > key)j--;//控制j从后往前找第一比key小的
    while (i < j)
    {
    if (a[j] == key)//在右边找到和枢轴相同的数放到数组最右端
    {
    int term;
    term = a[count2];
    a[count2] = a[j];
    a[j] = term;//在右边找到和枢轴相同的数放到数组最右端
    count2--;
    j--;
    while (i < j && a[j] > key)j--;//找到和key相同的数移动后还要继续找比key小的
    }
    else
    {
    a[i++] = a[j];//因为轴值已经记录为key,而a[0]为轴值
    break;//加个break是为了一旦找到比key值小的就不再循环
    }

    }
    while (i < j && a[i] < key)i++;//控制i从右往左找第一个比key大的
    while (i < j)
    {
    if (a[i] == key)//在左边找到的和key相同的值放到数组最左端
    {
    int term;
    term = a[count1];
    a[count1] = a[i];
    a[i] = term;//在左边找到的和key相同的值放到数组最左端
    count1++;
    i++;
    while (i < j && a[i] < key)i++;
    }
    else
    {
    a[j--] = a[i];
    break;
    }

    }
    }

    a[i] = key;//现在a[i]里面值并不是key而是最近比key大或者小的值,
    //但是已经赋值给了i或者j最近变动的地方,所以要复制key,也没有事情,
    //接下来应该把和枢轴相同的数放在枢轴相邻的位置
    int pivot = i;//用一个变量保存当前枢轴位置,因为下边ij都变了,
    for (int t1 = L;t1 < count1;t1++)//最左边与key值相同的数,与i左边的值交换
    {
    int term;
    term = a[--i];
    a[i] = a[t1];
    a[t1] = term;
    }
    for (int t2 = R;t2 > count2;t2--)//最左边与key值相同的数,与i左边的值交换
    {
    int term;
    term = a[++j];
    a[j] = a[t2];
    a[t2] = term;
    }

    cout << endl;
    int num = count1 + R - count2+1-L;
    max = max > num ? max : num;
    if (num < pivot - count1) return quicksort(a, L, pivot - count1 - 1 + L,max);
    if (num < count2 - pivot) return quicksort(a, pivot + R - count2 + 1, R,max);
    return max;
    }
    }

    int main()
    {

    int num=15;
    int max = 1;
    cout << "请输入排序的规模!" << endl;
    cin >> num;
    int *a = new int[num];//动态数组
    cout << "请输入数组!" << endl;
    for (int i = 0;i < num;i++)
    {
    cin >> a[i];
    }

    cout << "输出原始数组!" << endl;
    for (int i = 0;i < num;i++)
    {
    cout << a[i] << " ";
    }
    cout << endl;

    cout<<quicksort(a, 0, num - 1,max)<<endl;
    return 0;
    }

  • 相关阅读:
    iOS深入学习(Block全面分析)
    iOS 多快好省的宏定义
    1.ARC和非ARC文件共存
    简单的实现UIpicker上面的取消确定按钮
    ios 简单的倒计时验证码数秒过程实现
    jquerymobile 基础教程
    得到UIView中某个非子视图在UIView中的位置
    状态栏问题
    html表格,列表
    html简单样式
  • 原文地址:https://www.cnblogs.com/working-in-heart/p/9840358.html
Copyright © 2011-2022 走看看