Blue Bridge —— —— —— & C++ A Group 4 —— Quick Sorting

Keywords: less

subject

Sorting is often used in various situations.
Quick sorting is a very common and efficient algorithm.

The idea is to choose a "ruler" first.
Use it to sift through the entire queue.
To ensure that: its left element is not greater than it, its right element is not less than it.

In this way, the sorting problem is divided into two subintervals.
Sort the subintervals separately.

The following code is an implementation. Please analyze and fill in the missing code in the underlined part.

#include <stdio.h>

void swap(int a[], int i, int j)
{
	int t = a[i];
	a[i] = a[j];
	a[j] = t;
}

int partition(int a[], int p, int r)
{
    int i = p;
    int j = r + 1;
    int x = a[p];
    while(1){
        while(i<r && a[++i]<x);
        while(a[--j]>x);
        if(i>=j) break;
        swap(a,i,j);
    }
	______________________;
    return j;
}

void quicksort(int a[], int p, int r)
{
    if(p<r){
        int q = partition(a,p,r);
        quicksort(a,p,q-1);
        quicksort(a,q+1,r);
    }
}

int main()
{
	int i;
	int a[] = {5,13,6,24,2,8,19,27,6,12,1,17};
	int N = 12;

	quicksort(a, 0, N-1);

	for(i=0; i<N; i++) printf("%d ", a[i]);
	printf("\n");

	return 0;
}

Note: Only fill in the missing content, do not write any existing code or explanatory text.

Code

#include <stdio.h>
#include <iostream>
using namespace std;
void swap(int a[], int i, int j)
{
    int t = a[i];
    a[i] = a[j];
    a[j] = t;
}

int partition(int a[], int p, int r)
{
    int i = p;
    int j = r + 1;
    int x = a[p];//Value of left endpoint
    while(1){
        while(i<r && a[++i]<x);
        while(a[--j]>x);
        if(i>=j) break;
        swap(a,i,j);
    }
//    ______________________;
    swap(a,p,j);
    return j;
}

void quicksort(int a[], int p, int r)
{
    if(p<r){
        int q = partition(a,p,r);
        quicksort(a,p,q-1);
        quicksort(a,q+1,r);
    }
}

int main()
{
    int i;
    int a[] = {5,13,6,24,2,8,19,27,6,12,1,17};
    int N = 12;

    quicksort(a, 0, N-1);

    for(i=0; i<N; i++)
        printf("%d ", a[i]);
    printf("\n");

    return 0;
}

Posted by r3dk1t on Fri, 15 Mar 2019 07:00:27 -0700