Sunday, September 25, 2016

Chandu and his girlfriend - Understanding sorting algorithms

Chandu's girlfriend loves arrays that are sorted in non-increasing order. Today is her birthday. Chandu wants to give her some sorted arrays on her birthday. But the shop has only unsorted arrays. So, Chandu bought T unsorted arrays and is trying to sort them. But, he doesn't have much time to sort the arrays manually as he is getting late for the birthday party. So, he asked you to write a program to sort the T arrays in non-increasing order. Help him, or his girlfriend will kill him.

Input:
First line contains an integer T, denoting the number of test cases.
First line of each test case contains an integer N, denoting the size of the array.
Second line contains N space separated integers, denoting the array elements Ai.

Output:
For each test case, print the sorted array in non-increasing order.

Constraints:
1 <= T <= 100
1 <= N <= 105
0 <= Ai <= 109
SAMPLE INPUT

2
5
2 5 2 4 3
5
5 4 2 3 1

SAMPLE OUTPUT

5 4 3 2 2
5 4 3 2 1

Code :

#include<iostream>
using namespace std;
void bubblesort(long long int ar[], int n);
void selection_sort(long long int ar[], int n);
void swap(long long int *a, long long int *b);
int main(){
    int t;
    long long int n, i;
 
    cin>>t;
    while(t--){
        cin>>n;
        long long int ar[n];
        for(i=0;i<n;i++){
            cin>>ar[i];
        }
        // bubblesort(ar, n);
        selection_sort(ar, n);
        for(i=n-1;i>=0;i--){
            cout<<ar[i]<<" ";
        }
        cout<<endl;
    }
    return 0;
}
void bubblesort(long long int ar[], int n){
    int temp;
    for(int k=0;k<n-1;k++){
        for(int i=0;i<n-k-1;i++){
            if(ar[i]>ar[i+1]){
                temp = ar[i];
                ar[i] = ar[i+1];
                ar[i+1] = temp;
            }
        }
    } 
}

// The code is not showing any error but for the big numbers it's showing time limit exceeding so we have to use some other sorting algorithm.
// let's try implementing selection sort on this problem and see the result, if we get positive feedback from the compiler for larger inputs.
// here is the algorithm.
void selection_sort(long long int a[], int n){
    int min;
    for(int i=0;i<n-1;i++){
        // let's assume first element to be minimum
        min = i;
        for(int j=i+1;j<n;j++){
            if(a[j]<a[min]){
                min = j;
            }
        }
        swap(&a[i], &a[min]);
    }
}

void swap(long long int *a, long long *b){
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
// After executing this program we understand that the time complexity of both the algorithms i.e bubble sort and selection sort is O(n^2) i.e Big O of n square.
// we have to use yet another efficient algorithm for that.

No comments:

Post a Comment

Search This Blog