Why does this quicksort program not give an output? - c++

I am giving an integer array as input to an int array and I am expecting an output of sorted ints.
But there is no output.
I tried to use a recursive quicksort algo that will take an array of ints as input and give out a sorted array as output. I was expecting the sorted array to be shown in the terminal but there was no output.
This is the code
#include <iostream>
#define SIZE 10
using namespace std;
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int* array,int p, int q)
{
int key = array[p];
int i = p;
for(int j = p+1; j <= q; j++ )
{
if(key > array[j])
{
i++;
swap(&array[i],&array[j]);
}
}
swap(&array[i],&array[p]);
return i;
}
void quicksort(int* array,int p,int q)
{
if(p < q)
{
int r = partition(array,p,q);
quicksort(array,p,r-1);
quicksort(array,r,q);
}
}
int main()
{
int unsorted[SIZE] = {6,2,5,-1,11,3,17,-9,1,10};
quicksort(unsorted,0,SIZE-1);
cout << "The sorted array" << endl;
for(int i = 0; i < SIZE; i++)
{
cout << unsorted[i] <<" ";
}
}

The code you pasted enters infinite recursion in the quicksort function. Also, I would recommend using std::vector and pass that by reference instead of using C-style arrays. The std::vector is a more flexible container.
Here is the corrected code https://onlinegdb.com/q4LxWciVC:
#include <iostream>
#define SIZE 10
using namespace std;
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int* array,int p, int q)
{
int i = p-1;
int pivot = array[q]; // make pivot the last element of the array
for (int j{p};j<q;++j)
{
if (array[j] < pivot)
{
i++;
swap(&array[i], &array[j]);
}
}
swap(&array[i+1], &array[q]);
return i+1;
}
void quicksort(int* array,int p,int q)
{
if(p >= q){
return;
}
std::cout<<"\n---------Reached here---------\n";
int r = partition(array,p,q);
quicksort(array, p, r-1);
quicksort(array, r+1, q);
}
int main()
{
int unsorted[SIZE] = {6,2,5,-1,11,3,17,-9,1,10};
quicksort(unsorted,0,SIZE-1);
cout << "The sorted array" << endl;
for(int i = 0; i < SIZE; i++)
{
cout << unsorted[i] <<" ";
}
}
Output:
---------Reached here---------
---------Reached here---------
---------Reached here---------
---------Reached here---------
---------Reached here---------
---------Reached here---------
The sorted array
-9 -1 1 2 3 5 6 10 11 17

Related

Can't figure out why my Print Array is replacing elements

I'm taking a C++ class and we've gotten to pointers. The assignment we've been given is to basically bubble sort an array that was read from a text file by passing pointers as parameters for various functions. I think I have a decent setup that outputs what I'm looking for, but for specific actions, I'm getting a zero as an element when there isn't one written to the array.
#include <iostream>
#include <fstream>
using namespace std;
int capacity;
int count;
int readData(int *&arr);
void swap(int *xp, int *yp);
void bsort(int *arr, int last);
void writeToConsole(int *arr, int last);
void bubble_sort(int *arr, int last, int(*ptr)(int, int));
int ascending(int a, int b);
int descending(int a, int b);
int main() {
int *whatever = NULL;
count = readData(whatever);
cout << "Raw array data:" << endl;
writeToConsole(whatever, capacity);
cout << "After simple bubble sort:" << endl;
bubble_sort(whatever, capacity, ascending);
writeToConsole(whatever, capacity);
cout << "Now descending:" << endl;
bubble_sort(whatever, capacity, descending);
writeToConsole(whatever, capacity);
return 0;
}
int readData(int *&arr) {
ifstream inputFile;
inputFile.open("data.txt");
if (!inputFile) {
cout << "Error!";
}
inputFile >> capacity;
arr = new int[capacity];
for(int i = 0; i < capacity; i++){
inputFile >> arr[i];
}
inputFile.close();
return capacity;
}
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bsort(int *arr, int last) {
int i, j;
bool swapped;
for (i = 0; i < last + 1; i++)
{
swapped = false;
for (j = 0; j < last-i; j++)
{
if (arr[j] > arr[j+1])
{
swap(arr[j], arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
void writeToConsole(int *arr, int last) {
cout << "[ ";
for(int i = 0; i < last; i++){
cout << arr[i] << " ";
}
cout << "]" << endl;
}
void bubble_sort(int *arr, int last, int(*ptr)(int, int)){
int i, j;
bool swapped;
for (i = 0; i < last; i++)
{
swapped = false;
for (j = 0; j < last-i; j++)
{
//Use the function pointer to determine which logic to use
if (ptr(arr[j] , arr[j+1]))
{
swap(arr[j], arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
int ascending(int a, int b){
return a > b;
}
int descending(int a, int b){
return a < b;
}
My output looks like this:
Raw array data:
[ 8 4 7 2 9 5 6 1 3 ]
After simple bubble sort:
[ 0 1 2 3 4 5 6 7 8 ]
Now descending:
[ 9 8 7 6 5 4 3 2 1 ]
Any ideas as to why my second sort is throwing in a zero? Thank you!
you have to do this change is in bubble_sort function
for (j = 1; j < last - i; j++)
{
//Use the function pointer to determine which logic to use
if (ptr(arr[j-1], arr[j]))
{
swap(arr[j-1], arr[j]);
swapped = true;
}
}

heapsort-code is not working

The following code is not working for heap sort. It looks ok to me. Can someone help me please? I have followed the pseudo code from CLRS, the sorted numbers are not being updated after the algorithm is traversed.
#include <iostream>
using namespace std;
void max_heapify(int *b, int i,int he_size)
{
int l,r,largest;
l=2*i;
r=(2*i+1);
if (l<=he_size && b[l]>b[i])
largest=l;
else largest=i;
if (r<=he_size && b[r]> b[largest])
largest=r;
if (largest!=i)
{
swap(b[i],b[largest]);
max_heapify(b,largest,he_size);
}
}
void build_max_heap(int *c,int h_size,int strlength)
{
for (int q=(strlength)/2;q==1;--q)
{
max_heapify(c,q,h_size);
}
}
void swap(int a, int b)
{
int c=b;
b=a;
a=c;
}
int main()
{
int length;
int heap_size;
cout<<"Enter the number of numbers to be sorted by heap sort"<<endl;
cin>>length;
int* a=NULL;
a=new int[length-1];
int temp;
cout<<"Enter the numbers"<<endl;
for(int i=0;i<length;i++)
{
cin>>temp;
*(a+i)=temp;
}
cout<<"The given numbers are:"<<endl;
for(int j=0;j<length;j++)
cout<<*(a+j)<<" "<<endl;
heap_size= length;
build_max_heap(a,heap_size,length);
for (int l=length;l==2;--l)
{
swap(a[1],a[length]);
heap_size=heap_size-1;
max_heapify(a,1,heap_size);
}
cout<<"The sorted numbers are:"<<endl;
for(int j=0;j<length;j++)
cout<<*(a+j)<<" "<<endl;
system("pause");
return 0;
}
The number of mistakes in your code is enormous. Sorry to say it.
void swap(int a, int b)
{
int c=b;
b=a;
a=c;
}
does nothing - a and b should be passed by link, not by value:
void swap(int &a, int &b)
{
int c=b;
b=a;
a=c;
}
for (int q=(strlength)/2;q==1;--q) is wrong. You meant for (int q=(strlength)/2;q>1;--q). Your loop is running only when q==1.
a=new int[length-1]; The size of array should be length, not length-1. And even though swap(a[1],a[length]); is wrong, because a[length] is out of array.
Also there are some mistakes in algorithm. I tried to rewrite as less code as possible.
Right code is:
#include <iostream>
using namespace std;
void sift_down(int *a, int start, int end) {
int root = start;
while (root * 2 + 1 <= end) {
int child = root * 2 + 1;
int sw = root;
if (a[sw] < a[child])
sw = child;
if (child + 1 <= end and a[sw] < a[child + 1])
sw = child + 1;
if (sw == root)
return;
else
swap(a[root], a[sw]);
root = sw;
}
}
void max_heapify(int *b, int count) {
int start = (count - 2) / 2;
while (start >= 0) {
sift_down(b, start, count - 1);
--start;
}
}
void swap(int &a, int &b) {
int c = b;
b = a;
a = c;
}
int main() {
int length;
int heap_size;
cout << "Enter the number of numbers to be sorted by heap sort" << endl;
cin >> length;
int *a = new int[length];
cout << "Enter the numbers" << endl;
for (int i = 0; i < length; i++) {
cin >> a[i];
}
cout << "The given numbers are:" << endl;
for (int j = 0; j < length; j++)
cout << a[j] << " ";
cout << endl;
heap_size = length;
max_heapify(a, heap_size);
--heap_size;
while (heap_size) {
swap(a[heap_size], a[0]);
--heap_size;
sift_down(a, 0, heap_size);
}
cout << "The sorted numbers are:" << endl;
for (int j = 0; j < length; j++)
cout << a[j] << " ";
cout << endl;
//system("pause");
return 0;
}

After reading the theory of Merge Sort , I tried to write an implementation of Merge Sort, but its stuck

After reading through the theory of Merge Sort on TopCoder, I tried to write it's implementations, but it's getting weird, and I'm more or less a beginner in programming, especially algorithms. Can somebody assist me?
#include <iostream>
using namespace std;
int arr[] = {2, 0, 43, 12, 98};
int sizeOfarr(int a[])
{
return sizeof(a)/sizeof(a[0]);
}
int minElement(int x, int y)
{
if (x > y)
{
return y;
}
else if (x < y)
{
return x;
}
else
{
return x, y;
}
}
int main()
{
int t, z;
int n = sizeOfarr(arr);
int finalList[n];
int list1[n];
int list2[n];
for(int i = 0; i<=((n/2)-1); i++)
{
list1[i] = arr[i];
}
for(int j = n/2; j<n; j++)
{
for(int k = 0; k<=((n/2)-1); k++ )
{
list2[k] = arr[j];
}
}
for(int y = 0; y<=n; y++)
{
while(sizeOfarr(finalList)!=n)
{
t = list1[0];
z = list2[0];
finalList[y] = minElement(t, z);
if(finalList[y]==t)
{
list1[0] = list1[1];
}
else if(finalList[y]==z)
{
list2[0] = list2[1];
}
else
{
list1[0] = list1[1];
list2[0] = list2[1];
}
}
}
cout << "The sorted list is: " << finalList << endl;
return 0;
}
#include <iostream>
#include <math.h>
#include <string.h>
using namespace std;
int temp[10000];
void merge(int *A,int low,int mid,int high)
{
int i=low;
int j=mid+1;
int k=low;
int l;
while(i<=mid && j<=high)
{
if(A[i]<A[j])
{
temp[k]=A[i];
i=i+1;
}
else
{
temp[k]=A[j];
j=j+1;
}
k++;
}
for(l=i;l<=mid;l++,k++)
{
temp[k]=A[l];
}
for(l=j;l<=high;l++,k++)
{
temp[k]=A[l];
}
memcpy(A,temp,sizeof(A[0])*k);
}
void mergeSort(int *A,int low,int high)
{
int mid;
if(low<high)
{
mid=floor((low+high)/2);
mergeSort(A,low,mid);
mergeSort(A,mid+1,high);
merge(A,low,mid,high);
}
}
int main(int argc,char *argv[])
{
int n;
int array[10000];
cout<<"please enter the number numbers\n";
cin>>n;
cout<<"please enter the nubers\n";
for(int i=0;i<n;i++)
{
cin>>array[i];
}
mergeSort(array,0,n-1);
for(int i=0;i<n;i++)
{
cout<<array[i]<<" ";
}
cout<<"\n";
}
This is my implementation
mergeSort function divide recursively at middle and repeats until low lt(less than) high then a merge function is called.
I see from your code that the operator "," (return x,y) would replace x value by y value.
A few comments on the code:
return x,y // this just returns y. this is the case when x==y so it probably is OK bit not what one would write.
while(sizeOfarr(finalList)!=n) // The size of your array finalist is n elements. This is never going to change so this while condition is always false and the loop will never execute.

Build Max Heap algorithm won't work

I am trying to build a max heap using the algorithm given in Introduction to Algorithms, and I can't get it to work. Firstly, I'm having some interesting issues with passing arrays between functions. My understanding is that arrays are passed by reference in C++, but after I pass an array and I check the addresses of the argument and the parameter they don't match. When I try to use sizeof() on an array that is a parameter it doesn't return the correct value.
Secondly, the algorithm just doesn't seem to work. It does make some changes to the array, and gets the numbers closer to a heap but still has a ways to go. I've checked the code dozens of times and it seems to be spot on with pseudo code given in my text. What am I missing?
#include <iostream>
#include <ctime>
#define N 10
#define DISPLAY
using namespace std;
// Display an array
void display(double p[]) {
#ifdef DISPLAY
for (int i = 0; i < N; i++) cout << p[i] << " ";
cout << endl;
#endif
}
inline int parent(int i)
{return i/2;}
inline int left(int i)
{return 2*i;}
inline int right(int i)
{return 2*i+1;}
void maxHeapify(double p[], int i)
{
int largest;
int l = left(i);
int r = right(i);
if (l <= N && (p[l] > p[i]))
largest = l;
else
largest = i;
if (r <= N && (p[r] > p[largest]))
largest = r;
if (largest != i)
{
double temp = p[i];
p[i] = p[largest];
p[largest] = temp;
maxHeapify(p, largest);
}
}
void buildMaxHeap(double p[])
{
for (int i=N/2; i>0; i--)
maxHeapify(p, i);
}
int main() {
double a[] = {4,1,3,2,16,9,10,14,8,7};
buildMaxHeap(a);
display(a);
}
I modified your code as below:
#include <iostream>
#include <ctime>
#define N 10
#define DISPLAY
using namespace std;
// Display an array
void display(double p[]) {
#ifdef DISPLAY
for (int i = 0; i < N; i++) cout << p[i] << " ";
cout << endl;
#endif
}
inline int parent(int i)
{return i/2;}
inline int left(int i)
{return 2*i;}
inline int right(int i)
{return 2*i+1;}
void maxHeapify(double p[], int i)
{
int largest;
int l = left(i)-1;
int r = right(i)-1;
i=i-1;
if (l <= N && (p[l] > p[i]))
largest = l;
else
largest = i;
if (r <= N && (p[r] > p[largest]))
largest = r;
if (largest != i)
{
double temp = p[i];
p[i] = p[largest];
p[largest] = temp;
maxHeapify(p, largest+1);
}
}
void buildMaxHeap(double p[])
{
for (int i=N/2; i>0; i--)
maxHeapify(p, i);
}
int main() {
double a[] = {4,1,3,2,16,9,10,14,8,7};
buildMaxHeap(a);
display(a);
}

Quicksort algorithm with duplicate keys

I am trying to implement Quick Sort algorithm. Following code works for unique elements but it doesn't working for arrays having duplicate elements. Please tell me where I am doing wrong. Also when I change value of pivot to some other number other than 0 , program crashes. Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
void swapme(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void quicksort(int *arr, int size)
{
// these two variables will take care of position of comparison
int lower = 0, upper = size - 1;
int pivot = 0; // assigns pivot
if (size <= 1)
return;
while (lower < upper)
{
while (arr[lower] < arr[pivot])
{
++lower;
}
}
while (arr[upper] > arr[pivot])
{
--upper;
}
if (upper > lower)
{
swapme(arr[upper], arr[lower]);
// upper--;
// lower++;
}
quicksort(arr, lower);
quicksort(&arr[lower + 1], size - 1 - lower);
}
int main()
{
int arr[30];
for(int j = 0; j < 30; j++)
{
arr[j] = 1 + rand() % 5000;
}
for(int j = 0; j < 30; j++)
{
cout << arr[j] << "\t";
}
cout << endl;
quicksort(arr, 30);
for(int j = 0; j < 30; j++)
{
cout << arr[j] << "\t";
}
cout << endl;
cin.get();
cin.get();
}
Update: I have finally managed to make it work. Here is the fixed version:
void swapme(int &a, int &b )
{
int temp = a;
a = b;
b = temp;
}
void quicksort(int *arr, int size)
{
if (size <= 1)
return;
// These two variables will take care of position of comparison.
int lower = 0;
int upper = size-1;
int pivot = arr[upper/2]; // assigns pivot
while (lower <= upper)
{
while (arr[lower] < pivot)
++lower;
while (arr[upper] > pivot)
--upper;
if (upper >= lower)
{
swapme(arr[upper],arr[lower]);
if(arr[upper] == arr[lower])
{
// Can either increment or decrement in case of duplicate entry
upper--; // lower++;
}
}
}
quicksort(arr, lower);
quicksort( &arr[lower+1], size-1-lower);
}
You are storing the index of your pivot element in the pivot variable, so swapping the elements can potentially change the choice of pivot element during the loop. Not a very good idea. I would suggest storing the actual value of the pivot element inside pivot instead.
Also, if this really isn't homework, why don't you simply use the standard library facilities?
#include <algorithm>
// ...
std::sort(arr + 0, arr + 30);
You will get heavily optimized and tested code that will outperform your handwritten Quicksort anytime.
Quick Sort that can implement any number of i/p integers. it also deal with duplicate keys
#include <conio.h>
#include <string>
using namespace std;
void InputArray(int*,int);
void QuickSort(int *,int,int);
int partition(int *,int,int);
void swap(int *,int,int);
void printArr(int *,int Siz=11);
void main(){
int siz;
cout<<"Enter Array length : "; cin>>siz;
int *a=new int[siz];
InputArray(a,siz);
QuickSort(a,0,siz-1);
int i=0,j=11;
printArr(a,siz);
system("pause");
}
void InputArray(int*a,int s){
for(int i=0; i<s; i++){
cout<<"ELement ["<<i<<"] = "; cin>>a[i];
}
}
void QuickSort(int *a,int start,int end){
if(start<end){
int pivot=partition(a,start,end);
QuickSort(a,start,pivot);
QuickSort(a,pivot+1,end);
}
}
int partition(int *a,int start,int end){
int currentPivotValue=a[start];
int i=start-1, j=end+1;
while(true){
i++;
while(i<j && a[i]<currentPivotValue){ i++; }
j--;
while(j>start && a[j]>currentPivotValue) {j--;}
if(i<j) swap(a,i,j);
else return j;
}
}
void swap(int *b,int i,int j){
int t=b[i];
b[i]=b[j];
b[j]=t;
}
void printArr(int *a,int Siz){
for(int i=0; i<Siz; i++) cout<<a[i]<<" ";
}