快速排序-Sort The Array

Given a random set of numbers, Print them in sorted order.

Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.

Output:
Print each sorted array in a seperate line. For each array its numbers should be seperated by space.

Constraints:
1 ≤ T ≤ 10
1 ≤ N ≤ 1000
1 ≤A[i]<100

Example:
Input:
1
2
3 1

Output:
1 3

C++

#include <bits/stdc++.h>
using namespace std;
void swap(int* a, int* b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int partation(int arr[], int low, int high)
{
    int pivot = arr[high];
    
    int i = low - 1;
    
    for(int j=low; j<=high-1; j++)
    {
        if(arr[j]<=pivot)
        {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i+1], &arr[high]);
    return (i+1);
};

void quicksort(int arr[], int low, int high)
{

    if(low < high)
    {
        int pi = partation(arr, low, high);
        
        quicksort(arr, pi+1, high);
        quicksort(arr, low, pi-1);
    }
};

int main()
{
    //code
    int T;
    cin >> T;
    while(T--)
    {
        int N;
        cin >> N;
        int arr[N];
        
        for(int i=0; i<N; i++)
            cin >> arr[i];
        
        quicksort(arr, 0, N-1);
        
        for(int i=0; i<N; i++)
        {
            cout << arr[i] << ' ';
        }
        cout<<endl;
        
    }
    return 0;
}

python

#code
def partation(arr, low, high):
    pivot = arr[high]
    i = low - 1
    for j in range(low, high):
        if arr[j] < pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]
    
    arr[i+1], arr[high] = arr[high], arr[i+1]
    
    return (i+1)

def quicksort(arr, low, high):
    if low < high:
        pi = partation(arr, low, high)
        quicksort(arr, low, pi-1)
        quicksort(arr, pi+1, high)
   
T = int(input())
for i in range(0,T):
    arr_len = int(input())
    arr = list(map(int, input().split()))
    quicksort(arr, 0, arr_len-1)
    for i in range(0, arr_len):
        print("%d " %arr[i], end="")
    print()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容