fopen() gives me malloc(): corrupted top size - c++

I am trying to write the contents of an array, to a binary file, but it gives the following errors when I run the file.
malloc(): corrupted top size
Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
Here is my code
#include <iostream>
#include <time.h>
#include <fstream>
#include <iostream>
using namespace std;
#define ONE 1
#define TWO 2
#define THREE 3
#define FOUR 4
#define FIVE 5
#define SIX 6
#define SEVEN 7
int getArrayLength();
void initializeArray(int *array, int length);
void printArray(int *array, int length);
void menu(int *array, int length);
void userChoice(int userInput, int *array, int length);
void serialSearch(int *array, int length, int givenNumber);
void quickSort(int *array, int start, int end);
int partition(int *array, int start, int end);
void substitute(int *firstElement, int *secondElement);
int binarySearch(int *array, int start, int end, int userChoice);
void arrayConcatenation(int *firstArray, int *secondArray, int *concatenatedArray, int length, int doubleLength);
int main() {
int arrayLength = getArrayLength();
int *randomNumbersArray = (int *) malloc(arrayLength * sizeof (int));
initializeArray(randomNumbersArray, arrayLength);
printArray(randomNumbersArray, arrayLength);
menu(randomNumbersArray, arrayLength);
return 0;
}
int getArrayLength()
{
int size;
cout<<"Please give the size of the array: ";
cin>>size;
return size;
}
void initializeArray(int *array, int length)
{
srand(time(nullptr));
for(int i = 0; i < length; i++)
*(array + i) = 30 + rand() % 21;
}
void printArray(int *array, int length)
{
for(int i = 0; i < length; i++)
cout<<*(array + i)<<" ";
cout<<endl;
}
void menu(int *array, int length)
{
int userInput;
cout<<" Array Functions"<<"\n"<<endl;
do {
cout<<"1. Serial Search"<<endl;
cout<<"2. Array Classification"<<endl;
cout<<"3. Binary Search (classifies the array automatically)"<<endl;
cout<<"4. Concatenation of classified arrays"<<endl;
cout<<"5. Print"<<endl;
cout<<"6. Save and read array with binary file"<<endl;
cout<<"7. Exit"<<"\n"<<endl;
cout<<"Please enter your choice: ";
cout<<endl;
cin>>userInput;
userChoice(userInput, array, length);
} while (userInput != SEVEN);
}
void userChoice(int userInput, int *array, int length)
{
FILE *myFile;
int mergedLength = 2 * length;
int *secondArray = (int *) malloc(length * sizeof (int));
int *mergedArray = (int *) malloc(length * sizeof (int));
initializeArray(secondArray, length);
initializeArray(mergedArray, mergedLength);
switch(userInput)
{
case ONE:
{
int givenNumber;
serialSearch(array, length, givenNumber);
break;
}
case TWO:
{
quickSort(array, 0, length-ONE);
cout<<"This is the sorted array."<<endl;
printArray(array, length);
break;
}
case THREE:
{
int choice, existence;
cout<<"What number you want?"<<endl;
cin>>choice;
quickSort(array, 0, length-ONE);
existence = binarySearch(array, 0, length-ONE, choice);
if (existence == -ONE)
cout<<"The chosen number is not in the array."<<endl;
else
cout<<"The number is at index "<<existence<<"."<<endl;
break;
}
case FOUR:
{
quickSort(array, 0, length-ONE);
quickSort(secondArray, 0, length-ONE);
arrayConcatenation(array, secondArray, mergedArray, length, mergedLength);
quickSort(mergedArray, 0, mergedLength - ONE);
cout<<"This is the first array in order"<<endl;
printArray(array, length);
cout<<"This is the second array in order."<<endl;
printArray(secondArray, length);
cout<<"This is the merged array in order."<<endl;
printArray(mergedArray, mergedLength);
myFile = fopen("binarydata.dat", "wb");
if(myFile == NULL)
{
cout<<"Error in file opening."<<endl;
exit(0);
}
fwrite(array, sizeof (int ), length, myFile);
fclose(myFile);
break;
}
}
free(secondArray);
free(mergedArray);
}
void serialSearch(int *array, int length, int givenNumber)
{
int flag = -ONE;
cout<<"Please give the number that you want to find in the array: ";
cin>>givenNumber;
for(int i = 0; i < length; i++)
{
if(*(array + i) == givenNumber)
{
cout<<"The number was found at position: "<<i<<"\n"<<endl;
flag = 0;
break;
}
}
if(flag == -1)
cout<<"The number is not in the array."<<"\n"<<endl;
}
void quickSort(int *array, int start, int end)
{
if (start < end)
{
int driver = partition(array, start, end);
quickSort(array, start, driver-ONE);
quickSort(array, driver+ONE, end);
}
}
int partition(int *array, int start, int end)
{
int key = *(array + end);
int i = start - ONE;
for(int j = start; j < end; j++)
{
if(*(array + j) <= key)
{
i++;
substitute((array + i), (array + j));
}
}
substitute((array +i + ONE), (array + end));
return(i + ONE);
}
void substitute(int *firstElement, int *secondElement)
{
int temp = *firstElement;
*firstElement = *secondElement;
*secondElement = temp;
}
int binarySearch(int *array, int start, int end, int userChoice)
{
if(end >= start)
{
int middle = start + (end - start)/2;
if(*(array + middle) == userChoice)
return middle;
if(*(array + middle) > userChoice)
return binarySearch(array, start, middle-1, userChoice);
return binarySearch(array, middle+1, end,userChoice);
}
return -1;
}
void arrayConcatenation(int *firstArray, int *secondArray, int *concatenatedArray, int length, int doubleLength)
{
for(int i = 0; i < length; i++)
*(concatenatedArray + i) = *(firstArray + i);
for(int i = 0; i < length; i++)
*(concatenatedArray + i + length) = *(secondArray + i);
}
The problem is in the case FOUR of the switch case part of the code.

Related

All Strings of {A,C,T,G}

I'm currently working on a problem of solving the combination of the different length of {A,C,T,G}, from 1 letter to 6 letters.
For example:
------#=1------
1:A
2:C
3:G
4:T
------#=2------
1:AA
2:AC
3:AG
4:AT
5:CA
6:CC
7:CG
8:CT
9:GA
10:GC
11:GG
12:GT
13:TA
14:TC
15:TG
16:TT
------#=3------
1:AAA
2:AAC
3:AAG
4:AAT
5:ACA
.
.
.
Now I can only solve the combinations from 1 to 4 letters, and I have no idea how to solve the combination of {A,C,T,G} of 5 letters and 6 letters, which the length of the combination(5 and 6) is greater than the length of all the strings(4)....
Here is my code:
#include <iostream>
#include <cstdlib>
using namespace std;
void combinationUtil(char arr[], char data[], int start, int end, int index, int r);
void printCombination(char arr[], int n, int r)
{
char data[100];
combinationUtil(arr, data, 0, n-1, 0, r);
}
void combinationUtil(char arr[], char data[], int start, int end, int index, int r)
{
if (index == r) {
for (int j=0; j<r; j++)
cout << data[j];
cout << endl;
return;
}
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r);
}
}
int main()
{
char arr[] = {'A','T','C','G'};
int n = sizeof(arr)/sizeof(arr[0]);
printCombination(arr, n, 1);
printCombination(arr, n, 2);
printCombination(arr, n, 3);
printCombination(arr, n, 4);
printCombination(arr, n, 5);
system("pause");
}
At least assuming I understand what you want, this is pretty easy to solve by treating it as counting from 0 to some limit in base 4, with the "digits" displayed as "A", "C", "G" and "T".
#include <string>
#include <iostream>
std::string cvt(unsigned input, unsigned len) {
std::string ret;
static const char letters[] = "ACGT";
for (int i=0; i<len; i++) {
ret.push_back(letters[input%4]);
input /= 4;
}
return ret;
}
int main() {
unsigned limit = 1;
unsigned length = 4;
for (int i=0; i<4; i++)
limit *= 4;
for (int i=0; i<limit; i++)
std::cout << cvt(i, length) << "\n";
}
Your code assumes each letter can only be used once. That's why you are getting no results for both sequences of length 5 and 6. Rewrite your function as the following and do not pass as start or end value to it:
void combinationUtil(char arr[], char data[], int index, int r)
{
if (index == r)
{
for (int j=0; j<r; ++j)
cout << data[j];
cout << endl;
return;
}
for (int i=0; i<r; ++i)
{
data[index] = arr[i];
combinationUtil(arr, data, index+1, r);
}
}

Please help: [Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]

this is my first time here and I'm in a bit of a pickle. I have an assignment in class that asks the user which sorting algorithm do they want to sort in and my professor gave us a skeleton of the program already and all we have to do is to write the code of 3 sorting algorithms. It says that in line 41 I'm trying to pass a string with a char data type (my professor wrote that) and I'm stumped on how to fix it because I looked through the similar forum posts with people who have the same error as I and the solutions didn't work. Could you please take a look at the program to see what's wrong and how to fix it? I would deeply appreciate it.
#include <stdlib.h>
#include <time.h>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX_SIZE = 1000000;
// Set this to true if you wish the arrays to be printed.
const bool OUTPUT_DATA = false;
void ReadInput(string& sortAlg, int& size);
void GenerateSortedData(int data[], int size);
void GenerateReverselySortedData(int data[], int size);
void GenerateRandomData(int data[], int size);
void GenerateNearlySortedData(int data[], int size);
void Sort(int data[], int size, string sortAlg, char* dataType);
void InsertionSort(int data[], int size);
void MergeSort(int data[], int lo, int hi);
void combine(int data[], int size, int lo, int hi, int mid);
void QuickSort(int data[], int lo, int hi);
int partition(int data[], int lo, int hi);
void Swap(int &x, int &y);
bool IsSorted(int data[], int size);
void printData(int data[], int size, string title);
int main(void)
{
int size;
string sortAlg;
ReadInput(sortAlg, size);
int * data = new int[size];
GenerateSortedData(data, size);
Sort(data, size, sortAlg, "Sorted Data");
GenerateReverselySortedData(data, size);
Sort(data, size, sortAlg, "Reversely Sorted Data");
GenerateRandomData(data, size);
Sort(data, size, sortAlg, "Random Data");
GenerateNearlySortedData(data, size);
Sort(data, size, sortAlg, "Nearly Sorted Data");
cout << "\nProgram Completed Successfully." << endl;
return 0;
}
/********************************************************************/
void ReadInput(string& sortAlg, int& size)
{
cout << " I:\tInsertion Sort" << endl;
cout << " M:\tMergeSort" << endl;
cout << " Q:\tQuickSort" << endl;
cout << "Enter sorting algorithm: ";
cin >> sortAlg;
string sortAlgName;
if(sortAlg == "I")
sortAlgName = "Insertion Sort";
else if(sortAlg == "M")
sortAlgName = "MergeSort";
else if(sortAlg == "Q")
sortAlgName = "QuickSort";
else {
cout << "\nUnrecognized sorting algorithm Code: " << sortAlg << endl;
exit(1);
}
cout << "Enter input size: ";
cin >> size;
if(size < 1 || size > MAX_SIZE)
{
cout << "\nInvalid input size " << size
<< ". Size should be between 1 and " << MAX_SIZE << endl;
exit(1);
}
cout << "\nSorting Algorithm: " << sortAlgName;
cout << "\nInput Size = " << size << endl;
cout << endl;
}
/******************************************************************************/
void GenerateSortedData(int data[], int size)
{
int i;
for(i=0; i<size; i++)
data[i] = i * 3 + 5;
}
/*****************************************************************************/
void GenerateReverselySortedData(int data[], int size)
{
int i;
for(i = 0; i < size; i++)
data[i] = (size-i) * 2 + 3;
}
/*****************************************************************************/
void GenerateRandomData(int data[], int size)
{
int i;
for(i = 0; i < size; i++)
data[i] = rand();
}
/*****************************************************************************/
void GenerateNearlySortedData(int data[], int size)
{
int i;
GenerateSortedData(data, size);
for(i=0; i<size; i++)
if(i % 10 == 0)
if(i+1 < size)
data[i] = data[i+1] + 9;
}
/*****************************************************************************/
void Sort(int data[], int size, string sortAlg, char* dataType)
{
cout << endl << dataType << ":";
if (OUTPUT_DATA)
printData(data, size, "Data before sorting:");
// Sorting is about to begin ... start the timer!
clock_t start = clock();
if(sortAlg == "I")
InsertionSort(data, size);
else if(sortAlg == "M")
MergeSort(data, 0, size-1);
else if(sortAlg == "Q")
QuickSort(data, 0, size-1);
else
{
cout << "Invalid sorting algorithm!" << endl;
exit(1);
}
// Sorting has finished ... stop the timer!
clock_t end = clock();
double elapsed = (((double) (end - start)) / CLOCKS_PER_SEC) * 1000;
if (OUTPUT_DATA)
printData(data, size, "Data after sorting:");
if (IsSorted(data, size))
{
cout << "\nCorrectly sorted " << size << " elements in " << elapsed << "ms";
}
else
cout << "ERROR!: INCORRECT SORTING!" << endl;
cout << "\n-------------------------------------------------------------\n";
}
/*****************************************************************************/
bool IsSorted(int data[], int size)
{
int i;
for(i=0; i<(size-1); i++)
{
if(data[i] > data[i+1])
return false;
}
return true;
}
/*****************************************************************************/
void InsertionSort(int data[], int size)
{
//Write your code here
int i, j, temp;
for(i = 1; i < size; i++) //first element in the array
{
temp = data[i]; //Data[i] values are stored in temp.
while(j > 0 && data[j-1] > data[j]) //While j > 0 and the value of j-1 position is greater
{ //than the value of position j, begin swap.
temp = data[j]; //Value of data[j] is moved to temp.
data[j] = data[j-1]; //The values of data[j-1] is moved to data[j].
data[j-1] = temp; //Then the temp value is moved to the data[j-1] array.
j--; //Decrement j value.
}
}
}
/*****************************************************************************/
void MergeSort(int data[], int size)
{
//Write your code here
int hi, lo, mid;
if(lo <= hi)
{
mid = (hi + lo)/2; //Pivot.
MergeSort(data, lo, mid); //recurssively call lowerhalf of the array.
MergeSort(data, mid+1, hi); //recurssively call upperhalf of the array.
combine(data, size, lo, hi, mid); //combine the array.
}
return;
}
void combine(int data[], int size, int lo, int hi, int mid)
{
int temp[size];
int i = lo;
int j = mid+1;
int k = lo;
for(int i = lo; i <= hi; i++)
{
temp[i] = data[i]; //store the values in data array into the temp array
}
while(i <= mid && j <= hi)
{
if(temp[i] = temp[j]) //if i value in the temp array is equal to the j value in the temp array
{
data[k] = temp[i]; //move the temp[i] values into the main data[k] array
i++; //increment i by 1
}
else
{
data[k] = temp[j]; //otherwise, move the temp[j] values into the main array
j++; //increment j by 1
}
k++;
}
while(i <= mid)
{
data[k] = temp[i]; //while i value is <= to mid value, the temp[i] value is moved to data[k]
k++; //increment k
i++; //increment i
}
}
/*****************************************************************************/
void QuickSort(int data[], int size, int lo, int hi)
{
//Write your code here
int q;
if(lo>=hi)
{
q=partition(data, lo, hi);
QuickSort(data, lo, (q-1));
QuickSort(data, (q+1), hi);
}
}
int partition(int data[], int lo, int hi)
{
int temp; //temp for swaping
int i = lo;
int j = hi;
int pivot = data[(lo+hi)/2]; //pivot takes the end element
while(i<=j)
{
while(data[i] < pivot)
{
i++; //left hand side partition
}
while(data[j] > pivot)
{
j--; //right hand side partition
}
if(i <= j) //swaping occurs
{
temp = data[i]; //take data[i] and put it into temp
data[i] = data[j]; //take array sub data[j] values and put it into array sub data[i]
data[j] = temp; //take the temp values and put it into arra sub data[j]
i++;
j--;
}
}
}
/*****************************************************************************/
void Swap(int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}
/*****************************************************************************/
void printData(int data[], int size, string title) {
int i;
cout << endl << title << endl;
for(i=0; i<size; i++)
{
cout << data[i] << " ";
if(i%10 == 9 && size > 10)
cout << endl;
}
}
Character literals are char const(&)[].
So you can't pass them to char*. Instead, pass them as const char*, e.g.:
void Sort(int data[], int size, string sortAlg, const char* dataType)
You also have a variable lenth array (VLA) in line 265. That's a C99/C11 thing, and is not in C++.
The assignment here is wrong:
if(temp[i] = temp[j]) //if i value in the temp array is equal to the j value in the temp array
Write if(temp[i] == temp[j]) to compare ints.
partition (int partition(int data[], int lo, int hi)) has Undefined Behaviour because you don't return a value (and it's used)
You have missing code:
//Write your code here
int hi, lo, mid;
if(lo <= hi)
is also Undefined Behaviour because hi, lo are uninitialized there.
same in void InsertionSort(int data[], int size)
same in void Sort(int*, int, std::string, const char*)
void MergeSort(int data[], int lo, int hi); requires a definition (it's used)
void QuickSort(int data[], int size, int lo, int hi) has a redundant size argument that is not present in the declared prototype (line 27). Remove it
At least compiling code, not done the implementations for you:
Live On Coliru

Merging two arrays in ascending order

I know the logic how to merge two arrays but the problem is how to code.
This was my code n it is giving correct ans but my sir told me that do it again,please tell me what I have to add in this code,
#include<iostream>
using namespace std;
int mergeArrays(int array1[],int size1,int array2[],int size2);
int main()
{
const int size1=8;
const int size=12;
int arrayA[size1]={10,25,37,49,50,51,55,60};
int arrayB[size]={2,5,26,27,29,32,40,45,70,80,90,95};
mergeArrays(arrayA,size1,arrayB,size);
}
int mergeArrays(int array1[],int size1,int array2[],int size2)
{
int size3=size1+size2;
int *array3=new int[size3];
int k=0;
for(int i=0;i<size1;i++)
{
array3[k]=array1[i];
cout<<" "<<array3[k];
}
int j=0;
for(int i=size1;i<size2;i++)
{
array3[k]=array2[j];
}
for(int i=size1;i<size2;i++)
{
for(int j=0;j<size2;j++)
{
array3[i]=array2[j];
cout<<" "<<array3[i];
}
cout<<endl;
delete[]array3;
return array3[k++];
}
}
I had searched this in many places but could not corrected my code
I had written this code but it is not giving correct ans.
#include<iostream>
using namespace std;
int merge(int *a,int *b,int aSize,int bSize);
int main()
{
const int aSize={8};
const int bSize={12};
int arrayA[aSize]={10,25,37,49,50,51,55,60};
int arrayB[bSize]={2,5,26,27,29,32,40,45,70,80,90,95};
merge(arrayA,arrayB,aSize,bSize);
return 0;
}
int merge(int *a,int *b,int aSize ,int bSize)
{
int cSize=aSize+bSize;
int *c=new int[cSize];
int j=0,k=0;
int i=0;
while(i<=aSize&&j<=bSize )
{
if(a[aSize ]<=b[bSize])
{
c[k]=a[aSize];
k++;
i++;
}
else
{
c[k]=b[bSize];
k++;
j++;
}
}
for(int i=0;i<k;i++)
{
cout<<c[i]<<endl;
}
delete[]c;
return c[k++];
}
your sir request you do Merging two arrays in ascending order. so i think you should return a new array, fill with array1 and array2's element, and the elements should be ascending order. here is a implement.(suppose your input arraies is already in ascending order.)
#include <iostream>
using namespace std;
int mergeArrays(int array1[],int size1,int array2[],int size2, int outArray[]);
int main()
{
const int size1=8;
const int size=12;
int arrayA[size1]={10,25,37,49,50,51,55,60};
int arrayB[size]={2,5,26,27,29,32,40,45,70,80,90,95};
int outArray[size1+size];
int len = mergeArrays(arrayA,size1,arrayB,size, outArray);
cout <<" "<< len;
for (int i = 0; i< size1+size; ++i){
cout <<" " << outArray[i];
}
}
int mergeArrays(int array1[], int size1, int array2[], int size2, int outArray[])
{
int i=0, j=0, k=0;
int retSize = size1+size2;
while (k<retSize){
if (i==size1){// only left array2, copy it
for (; j<size2; ++j){
outArray[k++] = array2[j];
}
}else if (j == size2) { // only left array1, copy it
for (; i<size1; ++i){
outArray[k++] = array1[i];
}
}
else if (array1[i] > array2[j]){ // copy the min value to outArray
outArray[k++] = array2[j++];
}else{
outArray[k++] = array1[i++];
}
}
return k;
}
now, let's look at your first code:
int mergeArrays(int array1[],int size1,int array2[],int size2)
{
int size3=size1+size2;
int *array3=new int[size3];
int k=0;
for(int i=0;i<size1;i++)
{
array3[k]=array1[i]; // k is not changed, so you just assign array1's each value to array3[0]
cout<<" "<<array3[k];
}
int j=0;
// what's the purpose of this loop?
// and in loop, you don't use i, you just repeat set array3[0] = array2[0]!!
for(int i=size1;i<size2;i++)
{
array3[k]=array2[j];
}
for(int i=size1;i<size2;i++) // if array2's length bigger than array1's, will enter this loop.
{
for(int j=0;j<size2;j++)
{
array3[i]=array2[j]; // this just repeat assign array2's each value to array3[i]!!
cout<<" "<<array3[i];
}
cout<<endl;
delete[]array3;
return array3[k++]; // you delete array3, but at here you access it!! this will crash!
// also, in this for i loop, you have return, so it will only execute once.
}
// reach function end and no return if not enter for loop.
}
I haven't looked at your second code. I think you still need to do more study.

Count the number of component wise comparisons in quicksort algorithm.

I'm trying to count the number of comparisons my quicksort algorithm makes for an array size of 500. I know that the best case for quicksort with partition is nlogn-n+1. So for an array size of 500, the best case number of component wise comparisons would be about 3983. However, when I run my code, I'm getting 2400 comparisons or so, depending on the array the random function generates. Am I counting the number of component wise comparisons wrong? Please help.
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int count_500 = 0;
int partition(int *S,int l, int u);
void swap(int &val1, int &val2);
void Quicksort(int S[],int low, int hi);
void exchange(int list[], int p, int q);
int median_of_3(int list[], int p, int r);
void Quicksort_M3(int S[], int low, int hi);
int main()
{
int S1_500[500];
int S2_500[500];
int S3_500[500];
int S1_200[200];
int S2_200[200];
int S3_200[200];
int S1_8[8];
int S2_8[8];
int S3_8[8];
srand ( time(NULL) );
for(int i=0; i<500; i++)
{
S1_500[i] = rand()%1000;
S2_500[i] = rand()%1000;
S3_500[i] = rand()%1000;
}
for(int i=0; i<200; i++)
{
S1_200[i] = rand()%500;
S2_200[i] = rand()%500;
S3_200[i] = rand()%500;
}
for(int i=0; i<8; i++)
{
S1_8[i] = rand()%100;
S2_8[i] = rand()%100;
S3_8[i] = rand()%100;
}
Quicksort(S1_500,0,499);
for(int i=0; i<500; i++)
{
cout << S1_500[i] << endl;
}
cout << "Number of component wise comparisons is: " << count_500 << endl;
}
int partition(int *S,int l, int u)
{
int x = S[l];
int j = l;
for(int i=l+1; i<=u; i++)
{
if(S[i] < x)
{
count_500++; // Count the component wise comparison
j++;
swap(S[i],S[j]);
}
}
int p = j;
swap(S[l],S[p]);
return p;
}
void swap(int &val1, int &val2)
{
int temp = val1;
val1 = val2;
val2 = temp;
}
void Quicksort(int S[],int low, int hi)
{
if (low < hi)
{
int p = partition(S,low,hi);
Quicksort(S,low,p-1);
Quicksort(S,p+1,hi);
}
}
You want the count_500++; outside the if statement. You're only counting the comparisons, where the result is true.
Change
if(S[i] < x)
{
count_500++; // Count the component wise comparison
...
}
to
count_500++; // Count the component wise comparison
if(S[i] < x)
{
...
}

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]<<" ";
}