Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 42 additions & 50 deletions Ch 1.Arrays And Strings/10.Ouicksort.cpp
Original file line number Diff line number Diff line change
@@ -1,66 +1,58 @@
#include <iostream>
using namespace std;

int partition(int *arr,int low,int high);
int partition(int *arr, int low, int high) {
int pivot = arr[low];
int i = low, j = high + 1;

void quick(int *arr,int low,int high){
if(high>low){
int cnst=partition(arr,low,high);
quick(arr,low,cnst-1);
quick(arr,cnst+1,high);
}
}

int partition(int *arr,int low,int high){
int pivot=arr[low];
int i=low,j=high+1;
while (i < j) {
do {
++i;
}
while (arr[i] <= pivot);

while(i<j){

do{
i++;
}
while(arr[i]<=pivot);
do {
--j;
}
while(arr[j] > pivot);

do{
j--;
}
while(arr[j]>pivot);
if (i < j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why don't use std::swap ?

}
}

if(i<j){
int tmp=arr[i];
arr[i]=arr[j];
arr[j]=tmp;
}
int tmp = arr[low];
arr[low] = arr[j];
arr[j] = tmp;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why don't use std::swap?


return j;
}

int tmp=arr[low];
arr[low]=arr[j];
arr[j]=tmp;

/*for(int i=low;i<=high;i++)
cout<<arr[i]<<" ";
cout<<endl;*/

return j;
void quicksort(int *arr, int low, int high) {
if (high > low) {
int cnst = partition(arr, low, high);
quicksort(arr, low, cnst - 1);
quicksort(arr, cnst + 1, high);
}
}

int main(){

int n;
cout<<"Enter array size "<<endl;
cin>>n;
int main() {
int n;
std::cout << "enter array size : ";
std::cin >> n;

int arr[n];
cout<<"Enter array elements "<<endl;
int arr[n];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Variable length arrays are not of the C++ standard and are GCC extension only. std::vector<int> should be used.

std::cout << "enter array elements : ";

for(int i=0;i<n;i++)
cin>>arr[i];
for(int i = 0; i < n; ++i) {
std::cin >> arr[i];
}

quick(arr,0,n-1);
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
quicksort(arr, 0, n - 1);

for(int i = 0; i < n; ++i) {
std::cout << arr[i] << " ";
}
std::cout << "\n";
}