快速排序

来源:互联网 发布:ezdsdpro软件下载 编辑:程序博客网 时间:2024/06/15 08:09

本程序用vs编译

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

//

#include "stdafx.h"
#include<iostream>
#define N 50000+1
#include <fstream>
using namespace::std;
struct Node {
    int key;
    Node* next;
};
Node A[N];
void QuitSort(int i, int j);
int FindMax(int i,int j);
int PartSort(int i, int j, int node);
void Swap(Node &p, Node &q);
void Visit(Node A[N]);
int main()
{
    ifstream in;
    in.open("C:\\Users\\asus\\Documents\\Visual Studio 2017\\Projects\\QuikSort\\666.txt");
    if (in.fail())
    {
        cout << "ERROR!";
    }
    for (int opr = 1; opr < N; opr++)
    {
        in >> A[opr].key;
    }
    int i, j;
    cout << "Input start and destination:" << endl;
    cin >> i >> j;
    QuitSort(i,j);
    Visit(A);
    return 0;
}
void QuitSort(int i, int j) {
    int node;
    int k;
    int ord;
    ord = FindMax(i,j);
    if(ord != 0)
    {
        node = A[ord].key;
        k = PartSort(i, j, node);
        QuitSort(i, k - 1);
        QuitSort(k, j);
    }
}
int FindMax(int i,int j)
{
    int n=A[i].key;
    int k;
    for (k = i + 1; k <= j; k++)//forget '='
    {
        if (A[k].key > n)
            return k;
        if(A[k].key < n)
            return i;
    }
    return 0;
}
int PartSort(int i, int j, int node)
{
    int l = i;
    int r=j;
    do {
        Swap(A[l], A[r]);
        while (A[l].key < node)
        {
            l++;
        }
        while (A[r].key >= node)//等号一定要加在这两个if中的一个,为了将=node的结点挪到一侧
        {
            r--;
        }
    } while (l <= r);
    return l;
}
void Swap(Node &p, Node &q)
{
     Node temp;
    temp = p;
    p = q;
    q = temp;
}
void Visit(Node A[N])
{
    for (int i=1; i < N; i++)
    {
        cout << A[i].key << "   ";
    }
}
原创粉丝点击