Selection Sort Program with Comparison and Swap Counter | Code Help

  • Thread starter Thread starter heavyc
  • Start date Start date
  • Tags Tags
    Sort
Click For Summary
SUMMARY

The forum discussion centers on a C++ implementation of a selection sort algorithm that includes a comparison and swap counter. The user encountered four error messages due to missing a main() function, which is essential for executing any C++ program. Additionally, there are issues with the inclusion of headers and the use of the 'theArray' variable in the 'indexoflargest' function. The code requires corrections to compile and run successfully.

PREREQUISITES
  • C++ programming fundamentals
  • Understanding of sorting algorithms, specifically selection sort
  • Knowledge of function definitions and scope in C++
  • Familiarity with error handling in C++
NEXT STEPS
  • Implement a main() function to execute the selection sort program
  • Learn about C++ header files, specifically #include
  • Explore how to count comparisons and swaps in sorting algorithms
  • Study variable scope and parameter passing in C++ functions
USEFUL FOR

C++ developers, computer science students, and anyone interested in understanding sorting algorithms and debugging C++ code.

heavyc
Messages
16
Reaction score
0
Okay here's the deal I am writing a program so that i could put a counter into a selection sort and count the comparsions and the swaps but when i wrote thw code I get 4 error messages and I don't know why so here is the code if anyone can help it would be nice thank you
Code:
 #include <iostream.h>
#include <stdlib.h>
#include <cstddef>
typedef int Select;
void selectionsort(Select theArray[], int n)
{
n = 5;
for (int last = n-1; last >= 1; --last)
{
int largest = indexoflargest(theArray, last + 1);
swap(theArray[largest], theArray[last]);
}
}
int indexoflargest(const Select theArray[], int size)
{
int indexsofar = 0;
for (int currentindex = 1; currentindex < size; ++currentindex)
{
if(theArray[currentindex] > theArray[indexsofar])
indexsofar = currentindex;
}
return indexsofar;
}
void swap(Select& x, Select& y)
{
Select temp = x;
x = y;
y = temp;
}
 
Physics news on Phys.org
Perhaps sharing the error messages with us might help.
 
The error messages would help. And also, if that is your program in its whole, you don't have a main() function which every C program must have. There is nothing calling your predefined functions.
 

Similar threads

Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 8 ·
Replies
8
Views
3K
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
9
Views
2K
  • · Replies 12 ·
Replies
12
Views
3K