dimanche 27 septembre 2020

std::sort function is not sorting a vector, and I don't know why?

I have written a code to implement the quicksort algorithm in c++, it is working but the std::sort() function is not working at all. Please explain to me why.

#include "header.h"

using namespace std;
using namespace std::chrono;
bool myfunction (int i,int j) { return (i<j); }
int Partition(vector<int>& A, int start, int end){
    int pivot_idx = (rand() % (end - start + 1)) + start;
    Xswap(A[pivot_idx], A[end]);
    int pivot = A[end];
    int P_index = start;
    for(int i=start; i < end; i++){
        if(A[i] <= pivot){
            Xswap(A[i], A[P_index]);
            P_index++;
        }
    }
    Xswap(A[P_index], A[end]);
    return P_index;
}

void Qsort(vector<int>& A, int start, int end){
    if(start < end){
        int middle = Partition(A, start, end);
        Qsort(A, start, middle-1);
        Qsort(A, middle+1, end);
    }
}

void quick_sort(void){
    srand(time(NULL));
    int n;
    cin >> n;
    vector<int> v;
    v.reserve(n);
    //v.shrink_to_fit();
    
    for(int i=0; i<n; i++)
        v[i] = rand() % 1000;
    
    /*for(int i=0; i<n; i++)
        cout << v[i] << " ";
    cout << endl << endl;*/
    auto start = high_resolution_clock::now(); 
    
    //Qsort(v, 0, n-1);
    sort(v.begin(), v.end(), myfunction);
    
    auto stop = high_resolution_clock::now(); 
    auto duration = duration_cast<microseconds>(stop - start);
    for(int i=0; i<n; i++)
        cout << v[i] << " ";
    cout << endl;
    cout << duration.count() << endl; 
}

If you want to know what output is being shown upon calling executing the snippet: Program output

And if you want to see the contents of the header file:

#ifndef HEADER_H
#define HEADER_H

#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <vector>
#include <chrono>
#include <time.h>
void bble_sort(void);
void improved_bble_sort(void);
void quick_sort(void);
void ins_sort(void);
void Qsort(std::vector<int>& A, int start, int end);

template <typename T>
void Xswap(T& a, T& b);

#endif /* HEADER_H */

The vector in the output is completely unsorted; I have tried range-based for loop and iterators but nothing helped out. Please provide me some solutions or ideas, I'm completely confused.

Aucun commentaire:

Enregistrer un commentaire