lundi 5 octobre 2020

Problem in Quick sort implementation using C++: showing terminated your program because it exceeded the CPU usage limit

#include<iostream>
using namespace std;

void quick_sort(int arr[],int len, int ind){
    // len is length of an array
    //ind the is the index of an first element of an array
    int pivot=len-1;
    int right=len-2;
    int left= ind;
    int temp;

    if(left!=right||left<right && right>=0){
        while(left!=right || left!=right-1){
            if(arr[left]>arr[pivot] && arr[right]<arr[pivot]){
                temp=arr[left];
                arr[left]=arr[right];
                arr[right]=temp;
                left++;
                right--;

            }
            else if(arr[left]<arr[pivot]){
                left++;
            }
            else if(arr[right]>arr[pivot]){ right--;}

        }
        if(left==right||left==right-1){
            if(arr[left]>arr[right]){
               temp=arr[left];
                arr[left]=arr[right];
                arr[right]=temp; 
            }
                temp=arr[right];
                arr[right]=arr[pivot];
                arr[pivot]=temp;
                pivot=right;
        }
    }
    //quick_sort(arr,pivot-1, ind);
        //quick_sort(arr,len-pivot-1,pivot+1);
        for(int i=0;i<len;i++){
        std::cout<<arr[i]<<" ";
        }
}

int main(){
 
    int len;
    /*std::cout<<"Enter length of an array";
    std::cin>>len;
    int arr[20];

    for(int i=0;i<len;i++){
        std::cout<<"Enter element"<<i+1;
        std::cin>>arr[i];
    }*/
    int arr[] = {10, 7, 8, 9, 1, 5};
    quick_sort(arr,len,0);
    std::cout<<"Sorted array is";
    for(int i=0;i<len;i++){
        std::cout<<arr[i]<<" ";
    }

return 0;
}

Can somebody tell me what's the mistake that I'm unable to figure out????When I run this code: I get errors like time limit exceeded and Codeboard terminated your program because it exceeded the CPU usage limit.I will greatful if somebody help me out with my code.

Aucun commentaire:

Enregistrer un commentaire