Related
This question already has answers here:
How do I use arrays in C++?
(5 answers)
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 1 year ago.
I am trying to make a program that reads files with numbers and sort the numbers with different algorithms and there is multiple files that are going to be read and each file has a different amount of integers. so what i need to do is read those integers and cast them into a array.
but for some reason in c++ you cant have a array with an undefined size so what is a solution that i can use? And i can't use vectors (school project)
Here is my program
#ifndef SORT_H
#define SORT_H
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// =============================================================================
// FILE READER
// =============================================================================
void fileReader(string fileName, int arr[]){
ifstream myfile(fileName);
int pos = 0;
string number;
if(myfile.is_open()){
while (getline(myfile, number))
{
arr[pos] = stoi(number);
pos++;
}
}
}
// =============================================================================
// SWAPER
// =============================================================================
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// =============================================================================
// QUICKSORT
// =============================================================================
int partition(int arr[], int beg, int end){
int pivot = arr[end];
int index = beg - 1;
for(int j = beg; j < end; j++){
if(arr[j] <= pivot){
index++;
swap(&arr[index], &arr[j]);
}
}
swap(&arr[index+1], &arr[end]);
return (index+1);
}
void quicksortAlgo(int arr[], int beg, int end){
if(beg < end){
int pi = partition(arr, beg, end);
quicksortAlgo(arr, beg, pi-1);
quicksortAlgo(arr, pi+1, end);
}
}
template <typename T>
void quicksort(T arr[], int n)
{
quicksortAlgo(arr, 0, n-1);
for(int x = 0; x < n; x++)
cout << arr[x] << endl;
}
// =============================================================================
// HEAPSORT
// =============================================================================
void heapify(int arr[], int n, int i){
int max = i;
int left = 2*i + 1; // Left side
int right = 2*i + 2; // Right side
cout << "max: " << arr[max] << endl;
// if there is a left child for root and if is
// bigger then root
if(left < n && arr[max] < arr[left]){
max = left;
}
// If there is a right child of root and if is
// bigger then root
if(right < n && arr[max] < arr[right]){
max = right;
}
if(max != i){
swap(&arr[i], &arr[max]);
heapify(arr, n, max);
}
}
void heapsortAlgo(int arr[], int n){
for (int i = n/2 - 1; i >= 0; i--){
heapify(arr, n, i);
}
for (int i = n-1; i >= 0; i--){
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}
template <typename T>
void heapsort(T arr[], int n)
{
heapsortAlgo(arr, n);
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
}
// =============================================================================
// INTSERTIONSORT
// =============================================================================
template <typename T>
void insertionsort(T arr[], int n)
{
int holePostion;
int valueToInsert;
for (int i = 1; i < n; i++){
valueToInsert = arr[i];
holePostion = i;
while(holePostion > 0 && arr[holePostion-1] > valueToInsert){
arr[holePostion] = arr[holePostion - 1];
holePostion = holePostion - 1;
}
arr[holePostion] = valueToInsert;
}
}
int main(){
string filedest;
string arrSize;
cout << "enter file destenation: ";
cin >> filedest;
int arr[];
int n = sizeof(arr) / sizeof(arr[0]);
fileReader(filedest, arr);
quicksort(arr, n);
return 0;
}
#endif
As #MikeCAT mentioned, you can use std::vector<T>.
You can add push elements at the back of the vector by std::vector<T>::push_back().
Alternatively, you can also resize the vector array by using std::vector<T>::resize() and then add elements at a specific location similar to what you are doing in your fileReader() function. You can also insert elements at a specific location by calling std::vector<T>::insert()
.
Do have a look at the time complexities if you have a time constraint in your programming task.
So I've been having a problem with a c++ program that quicksorts an array of integers. When I have more than six elements in my array, the sort infinitely loops for some reason. I think I've isolated the problem to the choosing of mm pivotal value, but I can't work out for the life of me why it's causing it to break.
#include<iostream>
using namespace std;
int getPivot(int begin,int end){//Takes length of array as input and returns the position of the pivot
int len = end-begin;
if(len < 3){
return end;
}else{
return 2;
}
};
void quickSort(int begin, int end, int arr[]){
int pivot = arr[getPivot(begin,end)];//get Pivotal value - If I replace this with just 0 then there are no problems...
int tempLeft = begin, tempRight = end;
int temp;
while(tempLeft <= tempRight){
while(arr[tempLeft] < pivot){//Find a point where there are 2 elements that need to be swapped
tempLeft++;
}
while(arr[tempRight] > pivot){
tempRight--;
}
if(tempLeft <= tempRight){
temp = arr[tempLeft];//Swap the elements
arr[tempLeft] = arr[tempRight];
arr[tempRight] = temp;
tempLeft++;//Skip these swapped elements in the sort
tempRight--;
}
}
if (begin < tempRight){//Only recurse lower if the new sub array has a length greater than 1
quickSort(begin, tempRight, arr);
}
if (tempLeft < end){
quickSort(tempLeft, end, arr);
}
}
main() {
int array[] = {0,1,2,3,4,5,6};
int length = 7;
quickSort(0,length-1,array);
}
You will probably ask why I have such a weird way of choosing my pivotal value, but lets just say that for this instance the pivotal value has to be the third element in each sublist or if the sub list is smaller than 3 it is the last item in the sublist.
The reason I think the problem is associated with the pivotal value is because when I replace my method of choosing a pivot with just using the first element in the sublist I don't have any problems.
If run, as is now the program, will segfault after looping infinitely but if the array being sorted is one element shorter, it will work fine. That has had me baffled for hours now, and I can't work out what the problem is. If anyone has any tips or suggestions, they would be greatly appreciated.
quickSort(3,6,arr) will always call quickSort(3,6,arr).
I think you miss
int getPivot(int begin,int end)
{
//Takes length of array as input and returns the position of the pivot
int len = end-begin;
if(len < 3){
return end;
}else{
return 2+begin; // Here
}
};
EDIT: Clarification
GetPivot(3,6) will return 2, instead should return an index between 3 and 6.
You could also use the median of three approach for your pivot. It is a little more robust.
#include<iostream>
using namespace std;
void myswap(int* arr, int left, int right)
{
int swap = arr[left];
arr[left] = arr[right];
arr[right] = swap;
}
int getPivotIndex(int* arr, int begin, int end){
int middle = (begin + end) / 2;
if (arr[end] < arr[begin])
{
myswap(arr, begin, end);
}
if (arr[middle] < arr[begin])
{
myswap(arr, middle, begin);
}
if (arr[end] < arr[middle])
{
myswap(arr, end, middle);
}
return middle;
};
void quickSort(int begin, int end, int* arr){
int pivot = arr[getPivotIndex(arr, begin, end)];
int tempLeft = begin, tempRight = end;
while (tempLeft <= tempRight){
while (arr[tempLeft] < pivot){
tempLeft++;
}
while (arr[tempRight] > pivot){
tempRight--;
}
if (tempLeft <= tempRight){
myswap(arr, tempLeft, tempRight);
tempLeft++;
tempRight--;
}
}
if (begin < tempRight){
quickSort(begin, tempRight, arr);
}
if (tempLeft < end){
quickSort(tempLeft, end, arr);
}
}
int main() {
int array[] = { 6, 0, 2, 5, 4, 3, 1 }; // Test we are actually sorting
int length = 7;
quickSort(0, length - 1, array);
for (int i = 0; i < length; i++)
{
std::cout << "array[" << i << "]: " << array[i] << endl;
}
return 0;
}
I'm trying to create a program merge-sort on an array of int butI keep having troubles running this merge sort, it gives me a segment fault but I couldn't find anything wrong with it. In void mergesort when I put first <= last then the segment fault appears if not, then 5 5 5 5 is being print.
#include <iostream>
using namespace std;
void merge(int *arr, int size, int first, int middle, int last)
{
int temp[size];
for(int i = first; i<=last; i++)
{
temp[i] = arr[i];
}
int i=first, j=middle+1, k=0;
while(i<=middle && j<=last)
{
if(temp[i] <= temp[j])
{
arr[k] = temp[i];
i++;
}
else
{
arr[k]=temp[i];
j++;
}
k++;
}
while(i<=middle)
{
arr[k]=temp[i];
k++;
i++;
}
}
void mergesort(int *arr, int size, int first, int last)
{
if(first<last)
{
int middle = ( first + last )/2;
mergesort(arr,size,first,middle);
mergesort(arr,size,middle+1,last);
merge(arr,size,first,middle,last);
}
}
int main()
{
cout <<"Him";
const int size = 10;
int numbers [] = {5,10,1,6,2,9,3,8,7,4};
mergesort(numbers,size,0,9);
for( int i= 0; i<size; ++i)
{
cout << numbers[i] << " ";
}
return 0;
}
There are (at least) two bugs. This:
else
{
arr[k]=temp[i];
j++;
}
should be this:
else
{
arr[k]=temp[j];
j++;
}
and this:
int i=first, j=middle+1, k=0;
should be this:
int i=first, j=middle+1, k=first;
In general, you ought to learn to step through the code, at least by putting diagnostic output statements here and there. Once you have the hang of that you can move up to a good debugger.
The standard library already implements a function that merges correctly: std::inplace_merge. Implementation adapted from this more general post
void mergesort(int * first, int * last)
{
std::ptrdiff_t N = std::distance(first, last);
if (N <= 1) return;
int * middle = std::next(first, N / 2);
mergesort(first, middle);
mergesort(middle, last);
std::inplace_merge(first, middle, last);
}
int main()
{
cout <<"Him";
const int size = 10;
int numbers [] = {5,10,1,6,2,9,3,8,7,4};
mergesort(numbers, numbers+size);
for( int i= 0; i<size; ++i)
{
cout << numbers[i] << " ";
}
return 0;
}
Suggestion 1:
Instead of that line:
int temp[size];
If you need a dynamic size array use:
int temp = new int[size];
Then once you are done with it
delete[] temp;
Edit: As Neil suggested using std::vector is may be more useful than arrays in such situations (if you are allowed to use it).
Your code has 3 bugs, Also you can reduce your code length too if required.
void merge(int *arr, int size, int first, int middle, int last)
{
int temp[size];
for(int i = first; i<=last; i++)
temp[i] = arr[i];
int i=first, j=middle+1, k=first; // 1st Change, Set k to first instead of 0
while(i<=middle && j<=last)
{
if(temp[i] <= temp[j])
arr[k++] = temp[i++];
else
arr[k++]=temp[j++]; // 2nd Change, use j instead of i
}
while(i<=middle)
arr[k++]=temp[i++];
while(j<=last) // 3rd Change you missed this case
arr[k++]=temp[j++];
}
Live Code
The code that I have made for merge sort is given below. The thing is that on giving the input the output is 3 2 1 5 0. What is going wrong?
#include <iostream>
#include <cmath>
using namespace std;
int d[100];
void merge(int a[], int b[], int c[], int n)
{
int n2=floor(n/2);
int i=0, j=0, k=0;
while(i<n2 && j<(n-n2))
{
if(b[i]<c[j])
{
d[k++]=b[i++];
}
else if(b[i]>c[j])
{
d[k++]=c[j++];
}
}
if(i==n2)
{
if(j<(n-n2))
{
d[k++]=c[j++];
}
}
if(i<n2)
{
d[k++]=b[i++];
}
}
void mergesort(int a[], int n)
{
int n2=floor(n/2);
int b[50],c[50];
int i,j=0,k=0;
for(i=0;i<n2;i++)
{
b[i]=a[k++];
}
while(k<n)
{
c[j++]=a[k++];
}
merge(a,b,c,n);
}
int main()
{
int a[]={5,4,3,2,1};
int n=5;
mergesort(a,n);
for(int i=0;i<n;i++)
{
cout<<d[i]<<endl;
}
}
The main problem is that the arrays (b and c) passed to merge are not sorted.
Other problems are that the algorithm is not recursive and that merge
does not always put all numbers from b and c into a.
A version that seems to work with minimal changes to your code would be
void merge(int a[], int b[], int c[], int n)
{
int n2=floor(n/2);
int i=0, j=0, k=0;
while(k<n)
{
if((j == (n-n2) || b[i]<c[j]) && i < n2)
{
a[k++]=b[i++];
}
else
{
a[k++]=c[j++];
}
}
}
void mergesort(int a[], int n)
{
int n2=floor(n/2);
int b[50],c[50];
int i,j=0,k=0;
for(i=0;i<n2;i++)
{
b[i]=a[k++];
}
while(k<n)
{
c[j++]=a[k++];
}
if(n2 > 1) {
mergesort(b, n2);
}
if(n - n2 > 1) {
mergesort(c, n - n2);
}
merge(a,b,c,n);
}
int main()
{
int a[]={5,4,3,2,1};
int n=5;
mergesort(a,n);
for(int i=0;i<n;i++)
{
cout<<a[i]<<endl;
}
}
It is conventional to call merge_sort recursively in order to sort each subrange until the subrange is just one long then merge these together.
In your mergesort, b takes the first n/2 values of a, that is 5 and 4.
c takes the remaining values 3,2,1.
You then call merge (BTW Why do you pass a[] to this? It isn't used)
The first loop
while(i<n2 && j<(n-n2))
will have n2 = 2 and n-n2 = 5-2 = 3
This puts 3 at the start since b[0]>c[0]=3 and 2 next since b[1]>c[1]=2 and 1 at d[2] for similar reasons.
Since you don't recurse you won't sort these.
You then finish the while loop with i = 0 which is less than n2.
You just say
if(i<n2)
so you just copy the first thing from b which is 5.
All this gives 3, 2, 1, 5, and 0 because you made d global.
The input for merge need to be sorted arrays, as Philip mentioned before. Mergesort is recursive. For this you need to divide them till you reach a point where you only have one element in the array (so it is sorted) and merge all arrays to become the sorted result for the input. Wikipedia is your friend to understand the algorithm: Mergesort
Btw: You need to ensure that one of both cases in the comparison in the merge checks also on equality of the values.
Philip is right, there's no recursive in your code at all.
However, there are some more errors. I've marked it with annotations, just as a postscript of Philip's.
#include <iostream>
#include <cmath>
using namespace std;
int d[100];
void merge(int a[], int b[], int c[], int n)
{
int n2=floor(n/2);
int i=0, j=0, k=0;
while(i<n2 && j<(n-n2))
{
if(b[i]<c[j])
{
d[k++]=b[i++];
}
else if(b[i]>c[j])
{
d[k++]=c[j++];
}
/***************************************************/
/* What if b[i] == c[j] here? */
/* Your code will drop into an infinity loop. */
/***************************************************/
}
if(i==n2)
{
if(j<(n-n2))
/****************************************************/
/* Use **while** here? */
/* Because there may be more than one elements left */
/* in c[]. */
/****************************************************/
{
d[k++]=c[j++];
}
}
if(i<n2)
/***************************************************/
/* Use **while** here? - With the same reason */
/***************************************************/
{
d[k++]=b[i++];
}
}
void mergesort(int a[], int n)
{
int n2=floor(n/2);
int b[50],c[50];
int i,j=0,k=0;
for(i=0;i<n2;i++)
{
b[i]=a[k++];
}
while(k<n)
{
c[j++]=a[k++];
}
merge(a,b,c,n);
}
int main()
{
int a[]={5,4,3,2,1};
int n=5;
mergesort(a,n);
for(int i=0;i<n;i++)
{
cout<<d[i]<<endl;
}
}
template <typename T>
void merge(T arr[], int begin, int mid, int end)
{
int len = end - begin;
T *temp = new T[len];
int i = begin;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= end)
{
if(arr[i] <= arr[j])
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
while (i <= mid)
temp[k++] = arr[i++];
while(j <= end)
temp[k++] = arr[j++];
memcpy(arr + begin, temp, len*sizeof(T));
delete []temp;
}
template <typename T>
void mergeSort(T arr[], int begin, int end)
{
if (begin >= end)
return;
int mid = (end + begin) / 2;
mergeSort(arr, begin, mid);
mergeSort(arr, mid + 1, end);
merge(arr, begin, mid, end);
}
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]<<" ";
}