the program works but the problem is the sorted numbers doesnt appear. All it brings up is 1 and that's all. Where is the error?
#include <iostream>
using namespace std;
int const N = 20;
void pirmaisMasivs(int N);
int main (){
cout << "Numbers being sorted - 5,4,2,6,1,3,8,9,10,7 > " << pirmaisMasivs;
}
void pirmaisMasivs(int N){
int temp;
int masivs[10] = {5,4,2,6,1,3,8,9,10,7};
for( int i = 0; i < N - 1; i++ ){
for( int j = 0; j < N - 1; j++ ){
if( masivs[ j ] > masivs[ j + 1 ]){
temp = masivs[ j ];
masivs[ j ] = masivs[ j + 1];
masivs[ j + 1 ] = temp;
}
}
}
}
Your code has several problems.
First your declare your overall count of numbers to be sorted as int const N = 20;, but later you use 10 as a fixed literal count. The N = 20 is apparently wrong. The loops will cause an overrun of the array bounds.
Another problem is, that you do not output your sorted array in any means.
You just try call the sort method. Furthermore, you declare your array of integers to be sorted within your sort method, so you have no chance to access the sorted array outside of this method to print it.
Here is a completely reworked version of your program:
#include <iostream>
using namespace std;
int const N = 10;
int masivs[N] = {5,4,2,6,1,3,8,9,10,7};
void pirmaisMasivs() {
int temp;
for( int i = 0; i < N - 1; i++ ) {
for( int j = 0; j < N - 1; j++ ) {
if( masivs[ j ] > masivs[ j + 1 ]) {
temp = masivs[ j ];
masivs[ j ] = masivs[ j + 1];
masivs[ j + 1 ] = temp;
}
}
}
}
void printMasivs() {
for( int i = 0; i < N; i++ ) {
if ( i == 0 ) {
cout << masivs[ i ];
}
else {
cout << ", ";
cout << masivs[ i ];
}
}
}
int main () {
cout << "Numbers being sorted:\n";
printMasivs();
cout << "\n";
pirmaisMasivs();
cout << "\n";
printMasivs();
}
Related
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.
I have an 2d array of char, and I am trying to order them in alphabetical order. In each rows there is a word build of chars and I am trying to sort it.
I built something, but I don't understand why this is not working. If you have a solution for me, please explain what you are doing, in order to understand why I don't success.
Thanks !
char matrix[4][5] = {
{'h','e','l','l','o'},
{'r','e','a','d','y'},
{'a','p','p','l','e'},
{'p','o','i','n','t'},
};
char temp;
bool flag = false;
display(matrix);
for (int i = 0; i < 4 - 1; i++)
{
for (int rows = 0; rows < 10-1; rows++)
{
flag = false;
for (int cols = 0; cols < 5; cols++)
{
if (matrix[rows][cols] > matrix[rows + 1][cols])
{
flag = true;
break;
}
}
if (flag)
{
for (int index = 0; index < 5; index++)
{
temp=matrix[rows][index];
matrix[rows][index]=matrix[rows+1][index];
matrix[rows+1][index]=temp;
}
}
}
}
I will post this answer, even if it may not be what you want to do (but will be helpful for others who may want to do things this way).
Instead of sorting the 2D array, the trick is to not sort it, and instead sort an array of indices that point into the array. That is much more simpler than trying to manipulate the array itself.
Here is a very simple example:
#include <algorithm>
#include <cstring>
#include <iostream>
int main()
{
char matrix[4][5] = {
{'h','e','l','l','o'},
{'r','e','a','d','y'},
{'a','p','p','l','e'},
{'p','o','i','n','t'},
};
// create the indices
int index[] = { 0,1,2,3 };
// sort the indices based on the data in the array
std::sort(index, index + 4, [&](int n1, int n2)
{ return strncmp(matrix[n1], matrix[n2], 5) < 0; });
// Output the results
for (int i = 0; i < 4; ++i)
{
// Note how we access the original matrix using the index array
std::cout.write(matrix[index[i]], 5);
std::cout << " -- Using array at row " << index[i] << "\n";
}
}
Output:
apple -- Using array at row 2
hello -- Using array at row 0
point -- Using array at row 3
ready -- Using array at row 1
The final results show that the indices just point to the row that would be used if we want to access the array in a sorted manner. The original array was not adjusted.
That's it.
#include <bits/stdc++.h>
using namespace std;
char matrix[4][5] = {
{'h','e','l','l','o'},
{'r','e','a','d','y'},
{'a','p','p','l','e'},
{'p','o','i','n','t'} };
int n = 4, m = 5, k = 0;// number of rows and columns
char temp;
int main()
{
for ( int i = 0; i < n; i++ )
for ( int j = i + 1; j < n; j++ )
{
k = 0;
while ( matrix[i][k] == matrix[j][k] && k < m )
k++;
if ( k < m && matrix[i][k] > matrix[j][k] ) // ASCII code comparison
for ( int k = 0; k < m; k++ )
{
temp = matrix[i][k];
matrix[i][k] = matrix[j][k];
matrix[j][k] = temp;
}
}
for ( int i = 0; i < n; i++ )
{
for ( int j = 0; j < m; j++ )
cout << matrix[i][j];
cout << "\n";
}
}
I have to sort the matrix by the sum of the rows, the smallets sum has to be first and the the bigger and at the end has to be the biggest sum.
I have done this but I can't finish it:
#include <iostream>
using namespace std;
int main ()
{
int **matrix;
int i, j, count, row, col, sum, temp;
cout << "\n Enter the number of rows and columns";
cin >> row >> col;
matrix = new int *[row];
for (count = 0; count < row; count++)
matrix[count] = new int[col];
cout << "\nNow enter the element for the matrix.";
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
cout << "\nRow " << (i + 1) << " Col " << (j + 1) << " :";
cin >> *(*(matrix + i) + j);
}
}
for (i = 0; i < row; i++)
{
sum = 0;
for (j = 0; j < col; j++)
sum = sum + matrix[i][j];
cout << sum << endl;
}
for (int count = 0; count < row; count++)
delete[]matrix[count];
delete[]matrix;
matrix = 0;
return 0;
}
You can use standard algorithms std::sort and std::accumulate. Below there is a demonstrative program that shows how these algorithms can be used together.
#include <iostream>
#include <algorithm>
#include <numeric>
#include <cstdlib>
#include <ctime>
int main()
{
const size_t M = 3, N = 5;
std::srand( ( unsigned int )std::time( nullptr ) );
int **matrix = new int *[M];
for ( size_t i = 0; i < M; i++ ) matrix[i] = new int[N];
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) matrix[i][j] = std::rand() % ( M * N );
}
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) std::cout << matrix[i][j] << ' ';
std::cout << '\n';
}
std::cout << '\n';
auto sort_by_sum = [N]( const auto &left, const auto &right )
{
return std::accumulate( left, left + N, 0ll ) <
std::accumulate( right, right + N, 0ll );
};
std::sort( matrix, matrix + M, sort_by_sum );
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) std::cout << matrix[i][j] << ' ';
std::cout << '\n';
}
std::cout << '\n';
return 0;
}
The program output might look like
11 2 4 14 0
9 7 9 4 14
10 7 5 0 7
10 7 5 0 7
11 2 4 14 0
9 7 9 4 14
I wrote a selection sort program in C++. I have checked and rechecked the code, but the logic is perfectly fine. But the code is not sorting the array properly:
// Selection Sort
#include <iostream>
using namespace std;
inline void swap( int& x, int& y) {
int temp = x;
x = y;
y = temp;
}
int main() {
const int n = 10;
int list[n];
string line(14, '-');
cout << '\n' << line << "\nSelection Sort\n" << line << '\n';
cout << "Enter " << n << " elements:\n";
for( int i = 0; i < n; ++i ) {
cin >> list[i];
}
for( int i = 0; i < n-1; ++i ) {
int small = i;
for( int j = 1; j < n; ++j ) {
if( list[j] < list[small] ) {
small = j;
}
}
if( list[small] < list[i] ) {
swap( list[i], list[small]);
}
}
cout << "Sorted Array:\n";
for( int i = 0; i < n; ++i ) {
cout << list[i] << ' ';
}
return 0;
}
Where am I going wrong? The algorithm of Selection sort is given here: Selection Sort- wikipedia
Sample input with 10 numbers:
7 8 9 10 11 12 13 14 15 16
Output:
7 9 10 11 12 13 14 15 8 16
The inner loop is surely wrong here:
for( int j = 1; j < n; ++j ) {
should be
for( int j = i+1; j < n; ++j ) {
Also, the condition at the end of the loop
if( list[small] < list[i] ) {
swap( list[i], list[small]);
}
is excessive. It is satisfied by definition after the inner loop exits.
See: Sorting algorithms - selection sort for the pseudocode and a nicely animated demo on different kinds of data.
In the inner loop of the sorting loop, you have written: for( int j = 1; ...)
Now, every time, the inner loop is not going from 1 to n-1, but instead is going from i+1 to n-1
So change the loop to for( int j = i+1; ...)
Also, you may change the swapping condition to small != i, but this is optional.
I've inspected your code and you have a logic error for the selection sort to succeed. In the inner loop, the initialization of the inner loop is always j = 1. This should change to:
for( int j = i+1; j < n; ++j ) {
if( list[j] < list[small] ) {
small = j;
}
}
and also change the condition value of your outer loop to i < n to ensure the loop goes from start to end.
The inner loop should be
for(j=i+1;j<n;j++)
{
if( list[j] < list[small] ) {
small = j;
}
}
And if they small is not equal to I variable then swap
if(small != i)
{
swap();
}
#include <iostream>
using namespace std;
// Selection Sort function.
// Parameter 'a' is the size of the array.
void ss(int AR[] , int a) {
int small;
for (int i = 0 ; i <a ; i++) {
small = AR[i];
for (int j = i+1 ; j <a ; j++) {
if (AR[j]< small) {
int k = AR[j];
AR[j] = AR[i];
AR[i] = k;
}
}
}
}
int main() {
cout << "Enter the size of Your Aray";
int a;
cin >> a;
int AR[a];
cout << endl;
for (int i = 0; i < a; i++) {
cin >> AR[i];
cout << endl;
}
ss(AR, a);
cout << "The Sorted Array is";
for (int i=0; i < a; i++) {
cout << AR[i] << " ";
cout << endl;
}
}
When I enter the following:
15
6
13
22
23
52
2
The result returned is:
2
13
6
15
22
23
52
What is the bug preventing the list from being sorted numerically as expected?
The function can look like
void ss ( int a[], size_t n )
{
for ( size_t i = 0 ; i < n ; i++ )
{
size _t small = i;
for ( size_t j = i + 1; j < n ; j++ )
{
if ( a[j] < a[small] ) small = j;
}
if ( i != small )
{
int tmp = a[small];
a[small] = a[i];
a[i] = tmp;
}
}
}
It doesn't seem to be the SelectionSort I know. in the algorithm I know during every loop I look for the smallest element in the right subarray and than exchange it with the "pivot" element of the loop. Here's the algorithm
void selectionSort(int* a, int dim)
{
int posMin , aux;
for(int i = 0; i < dim - 1; ++i)
{
posMin = i;
for(int j = i + 1; j < dim; ++j)
{
if(a[j] < a[posMin])
posMin = j;
}
aux = a[i];
a[i] = a[posMin];
a[posMin] = aux;
}
}
and it seems that you change every smaller element you find, but also change the position of the "pivot". I hope the answer is clear.
Everything is ok in the original function, only that the small variable need to be refreshed when two vector elements will be switched.
Also in if statement set the small variable to the new value of AR[i].