Selection sort not grabbing last element in array - c++

void ProcessSort(int studentIDs[], string studentNames[], int num)
{
for (int i = 0; i < num - 1; i++)
{
int mindex = 0;
//DO6: finish the inner loop
// Hint: it should start from i+1 and go until num-1
// if studentNames[j] is greater than studentNames[mindex]
// then store j in mindex
for (int j = i+1; j < num - 1; j++) {
if (studentNames[mindex] < studentNames[j]) {
mindex = j;
}
}
//DO7: Swap student names
SwapNames(studentNames[mindex], studentNames[i]);
//DO8: Swap student IDs'
SwapIDs(studentIDs[mindex], studentIDs[i]);
}
cout << "Class List sorted by name." << endl;
}
Selection sort seems not to grab last element in array. There are two parallel arrays, one with names and one with ids, but it seems to be that the last name in the student names array isnt registered with the sort. Any help would be greatly appreciated.

The body of the outer loop should look at least like
int mindex = i;
//DO6: finish the inner loop
// Hint: it should start from i+1 and go until num-1
// if studentNames[j] is greater than studentNames[mindex]
// then store j in mindex
for (int j = i+1; j < num; j++) {
if (studentNames[mindex] < studentNames[j]) {
mindex = j;
}
}
This condition
if (studentNames[mindex] < studentNames[j]) {
provides sorting in the descending order.
Here is a demonstrative program.
#include <iostream>
#include <string>
#include <utility>
void ProcessSort( int studentIDs[], std::string studentNames[], size_t n )
{
for ( size_t i = 0; i < n; i++)
{
size_t mindex = i;
//DO6: finish the inner loop
// Hint: it should start from i+1 and go until num-1
// if studentNames[j] is greater than studentNames[mindex]
// then store j in mindex
for ( size_t j = i + 1; j < n; j++ )
{
if ( studentNames[mindex] < studentNames[j] ) mindex = j;
}
//DO7: Swap student names
if ( i != mindex )
{
std::swap( studentNames[mindex], studentNames[i] );
//DO8: Swap student IDs'
std::swap( studentIDs[mindex], studentIDs[i] );
}
}
}
int main()
{
int studentIDs[] = { 495, 520, 550, 666 };
std::string studentNames[] = { "Kyle", "Liam", "Bill", "Michael" };
const size_t N = sizeof( studentIDs ) / sizeof( *studentIDs );
for ( size_t i = 0; i < N; i++ )
{
std::cout << "( " << studentNames[i] << ", " << studentIDs[i] << " ) ";
}
std::cout << std::endl;
ProcessSort( studentIDs, studentNames, N );
for ( size_t i = 0; i < N; i++ )
{
std::cout << "( " << studentNames[i] << ", " << studentIDs[i] << " ) ";
}
std::cout << std::endl;
return 0;
}
Its output is
( Kyle, 495 ) ( Liam, 520 ) ( Bill, 550 ) ( Michael, 666 )
( Michael, 666 ) ( Liam, 520 ) ( Kyle, 495 ) ( Bill, 550 )

Related

Sort a matrix by the sum of the rows

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

Checking the numbers in an array and then comparing their values

Where do i fix the code in a way so that, i can check if the numbers in any row has equal values (e.g : if the matrix is 3*3 then for instance for the first row every number is 1)
#include <iostream>
using namespace std;
int main ()
{
int n;
cout<< "Kvadrat husnegtiin iremb:" <<endl ;
cin>> n;
int A[n][n];
for (int i = 0 ; i < n ; ++i )
{
for (int j = 0 ; j < n; ++j )
{
cout<< "["<< i<< "]"<< "["<< j<< "]"<< " Element"<< endl;
cin>> A[i][j] ;
}
}
for ( int i = 0 ; i < n ; ++i )
{
int B1 = A [i] [0] ;
for ( int j = 0 ; j < n; ++j )
{
if (B1 == A [i] [j] )
{
cout<< i<< "Baina"<< endl;
}
}
}
}
You can use a flag to check if there's a different value in your loop.
In example :
for (int i = 0; i < n; ++i)
{
int B1 = A[i][0];
bool IsDifferent = false;
for (int j = 0; !IsDifferent && j < n; ++j)
{
if (B1 != A[i][j]) //Notice the inverted condition
{
IsDifferent = true;
}
}
if (!IsDifferent)
cout << "Line " << i << " has equal values." << endl;
}
for ( int i = 0 ; i < n ; ++i ) {
bool all_equal = true;
for ( int j = 1 ; all_equal && j < n; ++j ) {
all_equal = A[i][j] == A[i][0];
}
if ( all_equal )
cout << "row " << i << " has equal values" << endl;
}

Bubble sort not working exactly

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();
}

Selection Sorting program showing abnormal results

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();
}

Incorrect Result from Selection Sort Algorithm

#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].