I am having a tough time trying to follow the logic here as to why it is not working correctly
expected output :
1 5 6 8
any help is greatly appreciated
Update: I got selection sort and insertion sort mixed up
OUTPUT:
unaltered array
5 8 1 6
1 -858993460 -858993460 6
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "SelectionSORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "SelectionSORT2\n";
}
cout << "SelectionSORT3\n";
}
#include <iostream>
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
UPDATE
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "Selection SORT1\n";
int I;
for (i = 0; i < n ; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = i;
int j;
for (j = i + 1;j < n ;j++)
{
std::cerr << j << ' ' << firstIndex << '\n';
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
swap(arr[i], arr[firstIndex]);
}
cout << " \n";
}
cout << " \n";
}
#include <iostream>
#include "BubbleSort.h"
#include "InsertionSort.h"
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
unaltered array
5 8 1 6
SelectionSORT1
1 0
2 0
3 2
2 1
3 2
3 2
5 6 1 8
You are using the selection sort method not the insertion sort method.
Bit in any case the function is incorrect
void InsertionSort(int *arr,int n)
{
cout << "INSERTION SORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "INSERTION SORT2\n";
}
cout << "INSERTION SORT3\n";
}
For starters it will not sort an array that has two elements due to this for loop
for (i = 0; i < n - 2; i++) //-1 ||-2//
Secondly, the variable firstIndex is not initialized by a value of the index i
firstIndex = arr[i];
So the condition in this if statement
if (arr[j] < arr[firstIndex])
does not make a sense.
Thirdly this inner for loop
for (j = i + 1;j < n - 1;j++)
ignores the last element of the array.
Fourth, this unconditional call of the function swap within the inner for loop
swap(arr[i], arr[firstIndex])
also does not make a sense.
The function can look the following way
void SelectionSort( int a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
size_t min = i;
for ( size_t j = i + 1; j < n; j++ )
{
if ( a[j] < a[min] )
{
min = j;
}
}
if ( min != i ) swap( a[i], a[min] );
}
}
And in main the variable size should have the type size_t - the type of the value of the expression with the operator sizeof
const size_t size = sizeof(array) / sizeof(array[0]);
And instead of the magic number 4 in for loops in main you should use the named constant size or you could use the range-based for loop as
for ( const auto &item : array )
{
cout << item << ' ';
}
cout << endl;
If you indeed mean the insertion sort method then a corresponding function can look for example the following way
void InsertionSort( int a[], size_t n )
{
for (size_t i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
int tmp = a[i];
size_t j = i;
for ( ; j != 0 && tmp < a[j - 1]; --j )
{
a[j] = a[j - 1];
}
a[j] = tmp;
}
}
}
Thank you all for your help
I got it to work like this
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void InsertionSort(int arr[],int n)
{
int i;
for (i = 0; i < n ; i++)
{
int firstIndex,j;
firstIndex = i;
for (j = i + 1;j < n ;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
}
swap(arr[i], arr[firstIndex]);
}
}
The following is C++:
std::set<int> sorted_array({ 5,8,1,6 });
If you have duplicates and need to keep them, use:
std::multiset<int> sorted_array({ 5,8,1,6 });
Done. One line.
Related
I wanted to write a program to take two arrays as input and convert the first array such that the difference of maximum value and minimum value from the first array gives the smallest possible number.
I tried to write a code to find a smaller number most closest to the maximum from the array in C++, but the function for finding the minimum works on Codelite, but not on other compilers;
Is there any fix to solve this, either to the code or the compiler?
Here is the code I tried:
#include <iostream>
using namespace std;
void swap(int A[], int B[], int n)
{
int x, y, temp;
for(x=0;x<n;++x)
{
for(y=0;y<n;++y)
{
if(A[x]>B[y])
{
temp = A[x];
A[x] = B[y];
B[y] = temp;
}
}
}
}
void sortas(int A[], int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = i; j < n; j++)
{
if (A[i] > A[j+1])
{
temp = A[i];
A[i] = A[j+1];
A[j+1] = temp;
}
}
}
}
int maxfind(int A[], int n)
{
int z, a;
a = A[0];
for(z=0;z<n;++z)
{
if(a<A[z])
{
a = A[z];
}
}
cout << "Max value in A is" << a << endl;
return a;
}
int minfind(int A[], int n, int amax, int amin)
{
int z, maxi;
maxi = amax;
for(z=0;z<n;++z)
{
if(maxi >= A[z])
{
amin = A[z];
}
else
{
maxi = maxi-1;
}
}
cout << "Mix value in A is" << amin << endl;
return amin;
}
int main() {
int z, t;
cout << "Enter number of test cases: ";
cin >> t;
int n, i, j, amax, amin;
for(z=0;z<t;++z)
{
cout << "Enter size of array" << endl;
cin >> n;
int A[n], B[n];
cout << "Enter Array A values:" << endl;
for(i=0;i<n;++i)
{
cin >> A[i];
}
cout << "Enter Array B values:" << endl;
for(j=0;j<n;++j)
{
cin >> B[j];
}
swap(A, B, n);
sortas(A, n);
cout << "Swapped and sorted array is: " << endl;
for(i=0;i<n;++i)
{
cout << A[i] << "\t" << B[i] << endl;
}
amax = 0;
amin = 0;
amax = maxfind(A, n);
amin = minfind(A, n, amax, amin);
}
return 0;
}
Here is the output to that code:
1 1 1 3 4 2
Max value in A is 1 Min value in A is 1
1 2 2
-1882830412 4 3 6 3
Max value in A is 2 Min value in A is -1882830412
The problem is with your bubble sort:
void sortas(int A[], int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = i; j < n; j++) // why not start at i + 1 ??
{
if (A[i] > A[j+1]) // j + 1 is out of bounds when j == n - 1
{
temp = A[i];
A[i] = A[j+1]; // <-- Some random value is written to A.
A[j+1] = temp; // <-- Overwriting some variable on the stack
// of main() (possibly B ?)
}
}
}
}
A correct bubble sort (this is not the pedantic bubble sort), this is probably the most used.
void sortas(int A[], int n)
{
for (int i = 0; i < n - 1; ++i)
{
for (int j = i + 1; j < n; ++j)
{
if (A[i] > A[j])
std::swap(A[i], A[j]);
}
}
}
The actual bubble sort algorithn (the "pedantic" bubble sort), swaps only occur on neighboring values.
void sortas(int A[], int n)
{
for (int i = 0; i < n - 1; ++i)
{
for (int j = 0; j < (n - i) - 1; ++j)
{
if (A[j] > A[j + 1])
std::swap(A[j], A[j + 1]);
}
}
}
Use one or the other, for integers, the performance is identical.
I want to count how many times does algorithm makes comparisons and how many times algorithm makes copying.
#include <stdio.h>
#include <random>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <time.h>
void generuoti(int _N, const char *_file);
void nuskaityti(const char *_file);
int ps = 0;
int ks = 0;
void heapify(double arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
ps+=1;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
ps += 1;
// If largest is not root
if (largest != i)
{
std::swap(arr[i], arr[largest]);
ps += 1;
ks += 1;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// pagr funkcija haep sortui
void heapSort(double arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--)
{
// Move current root to end
std::swap(arr[0], arr[i]);
ks+=1;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
void insertion_sort(double arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
ks+=1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
ks+=1;
ps+=1;
}
arr[j + 1] = key;
ks+=1;
}
}
using namespace std;
double *Data;
double* A;
double* B;
double N;
int main()
{
srand(time(NULL));
cout << "Generuojame atsitktinius duomenis" << endl;
generuoti(20000, "duom.txt");
cout << "Nuskaitome duomenis" << endl;
nuskaityti("duom.txt");
A = new double[(int)N];
B = new double[(int)N];//jeigu algoritmui reikia papildomo masyvo
for (int i = 0; i < N; i++) {
A[i] = Data[i];
}
cout << "Pradine skaiciu seka:" << endl;
for (int i = 0; i < N; i++)
cout << A[i] << " ";
cout << endl;
//
insertion_sort(A, N);
//heapSort(A, N);
//truksta veiksmu sk
cout << "Surusiuota skaiciu seka:" << endl;
for (int i = 0; i < N; i++)
cout << A[i] << " ";
cout << endl;
cout << "Kopijavimu skaicius " << ks << endl;
cout << "Palyginimu skaicius " << ps << endl;
system("pause");
return 0;
}
void generuoti(int _n, const char *_file) {
ofstream os(_file);
os << _n << endl;
for (int i = 0; i<_n; i++)
os << " " << 500+ (double)(rand() % 3001) ;
os.close();
}
void nuskaityti(const char *_file) {
ifstream is(_file);
if (is.fail()) {
cout << "Failo nera" << endl;
exit(1);
}
is >> N;
Data = new double[(int)N];
for (int i = 0; i < N; i++) {
is >> Data[i];
}
}
This is my code, and ps - is equal to a number of comparisons, and ks - is equal to number of copying. I want to ask if I counted all comparisons and all copying in the algorithms? Thanks for answers.
No
if (l < n && arr[l] > arr[largest])
largest = l;
ps+=1;
There are two problems here. Assuming you are talking about double comparisons (rather than integer), the comparison may or may not occur.
Secondly your indentation is deeply misleading. (You always increment.)
You need
if (l < n) {
ps++; // About to compare
if (arr[l] > arr[largest])
largest = l;
}
There are probably other errors, but it is impossible to tell because I can't read your language, so the printed text, comments, and names are meaningless.
Given you are writing in C++, I would write a class with operator <() and operator =, and a copy constructor, and instrument those. That way you cannot possibly get it wrong.
I wrote this solution for the absolute permutation problem on HackerRank. It works fine on dev-C++ but doesn't work on Hackerrank. I've found that the code produces output when I remove the abs_perm(). What's the problem here?
#include <iostream>
using namespace std;
int arr[100000];
int check(int n, int k)
{
if ( (2*k == n) || (k == 0) || (n - 4*k == 0) )
return 1;
else if (k < n/2)
return check(n - 4*k, k);
else
return 0;
}
void swap(int &a, int &b)
{
int c = b;
b = a;
a = c;
}
void ini(int n)
{
for (int i = 0; i < n; i++)
{
arr[i] = i+1;
}
}
void abs_perm(int n, int k)
{
for (int i = 0; i < k; i++)
{
swap(arr[i], arr[k+i]);
}
if (2*k == n)
return;
for (int i = n - 1; i > n - k - 1; i--)
{
swap(arr[i], arr[i-k]);
}
if (n - 4*k == 0)
return;
abs_perm(n - 4*k, k);
}
int main()
{
int T;
cin >> T;
int N[T], K[T];
for (int i = 0; i < T; i++)
{
cin >> N[i] >> K[i];
}
for (int i = 0; i < T; i++)
{
cout << N[i] << " " << K[i] << "\n";
}
for (int i = 0; i < T; i++)
{
if ( !check(N[i], K[i]) )
cout << "-1\n";
else
{
ini(N[i]);
abs_perm(N[i], K[i]);
for (int j = 0; j < N[i]; j++)
{
cout << arr[j] << " ";
}
cout << "\n";
}
}
return 0;
}
Array is a structure to use when you know at compile time the dimension of your structure. What you wrote at the begin in abs_perm() is not correct for standard compilers (in fact you don't know the dimension of your array). You can use a std::vector or a std::list which allocate memory dynamically or (bad solution) you can allocate an array with dimension that certainly contains all elements you will put inside.
I am trying to do a bubble sort, but I don't know what's happening in my code. I am a noob so sorry if the code I wrote seems obvious ^.^
main() {
int a[5], i, j, smallest, temp;
cout << "Enter 5 numbers: " << endl;
for ( i = 0; i <= 4; i++ ) {
cin >> a[i];
}
for ( i = 0; i <=4; i++ ) {
smallest = a[i];
for ( j = 1; j <= 4; j++ ) {
if ( smallest > a[j] ) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
cout << endl << endl;
for ( i = 0; i <= 4; i++ ) {
cout << a[i] << endl;
}
system("pause");
}
Any answer will be highly appreciated. Thanks!
Your bubblesort almost appears to be a selection sort. Bubblesort looks at pairs of items and swaps them if necessary. Selection sort looks for the lowest item in the rest of the array, and then swaps.
#include <iostream>
#include <utility>
using std::cin;
using std::cout;
using std::endl;
using std::swap;
void bubblesort(int a[5])
{
bool swapped = true;
while (swapped)
{
swapped = false;
for (int i = 0; i < 4; i++)
{
if (a[i] > a[i + 1])
{
swap(a[i], a[i + 1]);
swapped = true;
}
}
}
}
void selectionSort(int a[5])
{
for (int i = 0; i < 4; i++)
{
int smallest = i;
for (int j = smallest; j < 5; j++)
{
if (a[smallest] > a[j])
{
smallest = j;
}
}
if (smallest != i)
{
swap(a[i], a[smallest]);
}
}
}
int main(int argc, char* argv[])
{
int a[5];
cout << "Enter 5 numbers: " << endl;
for (int i = 0; i < 5; i++ )
{
cin >> a[i];
}
//selectionSort(a);
bubblesort(a);
cout << endl << endl;
for (int i = 0; i <= 4; i++ ) {
cout << a[i] << endl;
}
}
New to C++ and learning. This program returns the correct output. I changed the function prototype to void to isolate and make sure function is providing correct output.
#include <iostream>
#include <fstream>
void ArraySortToMedian(int x[], int numElem);
using namespace std;
int main()
{
ifstream infile;
infile.open("numbers.txt");
const int SIZE = 6;
int array[SIZE];
int i;
if(!infile)
{
cout << "couldn't find 'numbers.txt'";
return 1;
}
while(i < SIZE && infile >> array[i])
i++;
infile.close();
for(i = 0; i < SIZE; i++)
cout << array[i] << "\n";
ArraySortToMedian(array, SIZE);
return 0;
}
void ArraySortToMedian(int x[], int numElem)
{
bool swap;
int temp, i;
double m;
do
{
swap = false;
for(i = 0;i < (numElem - 1); i++)
{
if( x[i] > x[i + 1] )
{
temp = x[i];
x[i] = x[i + 1];
x[i + 1] = temp;
swap = true;
}
}
}
while (swap);
cout << "\n";
for(i = 0; i < numElem; i++)
cout << x[i] << "\n";
m = (x[numElem/2] + x[numElem/2]-1)/(double)2;
cout << "\n" << m;
}
Output:
6
5
3
1
2
4
1
2
3
4
5
6
3.5
When I remove void and replace it with double to return to main() the median value like this.
#include <iostream>
#include <fstream>
double ArraySortToMedian(int x[], int numElem);
using namespace std;
int main()
{
ifstream infile;
infile.open("numbers.txt");
const int SIZE = 6;
int array[SIZE];
int i;
double median;
if(!infile)
{
cout << "couldn't find 'numbers.txt'";
return 1;
}
while(i < SIZE && infile >> array[i])
i++;
infile.close();
for(i = 0; i < SIZE; i++)
cout << array[i] << "\n";
median=ArraySortToMedian(array, SIZE);
cout<< "\n" << median << "\n";
return 0;
}
double ArraySortToMedian(int x[], int numElem)
{
bool swap;
int temp, i;
double m;
do
{
swap = false;
for(i = 0;i < (numElem - 1); i++)
{
if( x[i] > x[i + 1] )
{
temp = x[i];
x[i] = x[i + 1];
x[i + 1] = temp;
swap = true;
}
}
}
while (swap);
cout << "\n";
for(i = 0; i < numElem; i++)
cout << x[i] << "\n";
m = (x[numElem/2] + x[numElem/2]-1)/(double)2;
return(m);
}
Distorted Output:
1
6
5
3
1
2
1
1
2
3
5
6
2.5
When returned its moving the elements of the array that are generated in main() when before when I simply outputted from ArraySortToMedian(). I assume that it has to do with me referencing the beginning address of the array first element.
Probably very simple but with my limited experience I'm at a loss with this behaviour. Any help so that I can learn what I'm doing wrong will be appreciated. Thank you.
The problem is your input loop:
int i;
// ... snip ...
while(i < SIZE && infile >> array[i])
i++;
You're never initializing i, so this is undefined behavior. Maybe it works maybe it doesn't.
If you used a std::vector instead of an array, this would be easier:
std::vector<int> values;
int next;
while (infile >> next) {
values.push_back(next);
}
And now you're neither size-limited nor do you have to worry about keeping track of an index.