While I'm pretty sure the number of location swaps for everything else is correct, the one for my InsertionSort function is showing up as zero.
I'm not sure why.
Any ideas on how to fix this logic error?
#include <iostream>
using namespace std;
const int SIZE=20;
void bubbleSort(int numbers[], int SIZE);
void selectionSort(int numbers[], int SIZE);
void insertionSort(int numbers[], int SIZE, int &a, int &b);
int main()
{
int numbers[SIZE]= {26, 45, 56, 12, 78, 74, 39, 22, 5, 90, 87, 32, 28, 11, 93, 62, 79, 53, 22, 51};
int value=0;
bool found;
int a;
int b;
cout << "Today we are going to be searching for values." << endl;
cout << "These are the values you have to choose from" << endl;
for (int i=0; i<SIZE; i++)
cout << numbers[i]<<"; ";
do
{
cout << "Make sure to enter a value that's in the list." << endl;
cin >> value;
found=false;
for (int i=0; i<SIZE; i++)
{
if (value==numbers[i])
{
found=true;
break;
}
}
if (!found)
cout << "Enter a valid value !" << endl;
}
while (!found);
bubbleSort(numbers, SIZE);
selectionSort(numbers, SIZE);
insertionSort(numbers, SIZE, a, b);
return 0;
}
void bubbleSort (int numbers[], int SIZE)
{
cout<<"\nOriginal order: ";
for(int i=0;i<SIZE;i++)
cout<<numbers[i]<<' ';
int maxElement;
int index,counter=0;
for(maxElement=SIZE-1; maxElement>=0; maxElement--)
{
for(index=0;index<=maxElement-1;index++)
{
if(numbers[index]>numbers[index+1])
{
swap(numbers[index], numbers[index+1]);
counter++;//increments counter everytime swap occurs
}
}
}
cout<<"\nBubble Sorted: ";
for(int i=0;i<SIZE;i++)
cout<<numbers[i]<<' ';
cout<<"\nNumbers of location swap: "<<counter<<endl;
}
void swap(int &a, int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void selectionSort(int numbers[], int SIZE)
{ cout<<"\nOriginal order: ";
for(int i=0;i<SIZE;i++)
cout<<numbers[i]<<' ';
int startScan;
int index;
int miniIndex;
int miniValue;
int counter=0;
for(startScan=0;startScan<(SIZE-1);startScan++)
{
miniIndex=startScan;
miniValue=numbers[startScan];
for(index=startScan+1;index<SIZE;index++)
{
if(numbers[index]<miniValue)
{
miniValue=numbers[index];
miniIndex=index;
}
}
swap(numbers[miniIndex], numbers[startScan]);
counter++;
}
cout<<"\nSelection Sorted: ";
for(int i=0;i<SIZE;i++)
cout<<numbers[i]<<' ';
cout<<"\nNumbers of location swap: "<<counter<<endl;
cout << endl;
}
void insertionSort(int numbers[], int SIZE, int &a, int &b)
{
int temp = a; a = b; b = temp;
int j, swap = 0;
cout<<"Original order: ";
for(int i = 0; i < SIZE; i++)
cout<< numbers[i] << ' ';
for (int i = 0; i < SIZE; i++){
j = i;
while (j > 0 && numbers[j] < numbers[j-1])
{
temp = numbers[j];
numbers[j] = numbers[j-1];
numbers[j-1] = temp;
j--; swap++;
}
}
cout <<"\nThe number of location swaps is: "<< swap << endl;
return;
}
You get 0 swaps for insertion sort because insertion sort performed 0 swaps, because the array was already sorted, because you ran bubble sort on it earlier.
You don't get 0 swaps for selection sort because your selection sort function always performs N-1 swaps, if N is the size of the array, even if the array is already sorted.
You don't get 0 swaps for bubble sort because the array isn't already sorted at that point.
Related
I'm taking a C++ class and we've gotten to pointers. The assignment we've been given is to basically bubble sort an array that was read from a text file by passing pointers as parameters for various functions. I think I have a decent setup that outputs what I'm looking for, but for specific actions, I'm getting a zero as an element when there isn't one written to the array.
#include <iostream>
#include <fstream>
using namespace std;
int capacity;
int count;
int readData(int *&arr);
void swap(int *xp, int *yp);
void bsort(int *arr, int last);
void writeToConsole(int *arr, int last);
void bubble_sort(int *arr, int last, int(*ptr)(int, int));
int ascending(int a, int b);
int descending(int a, int b);
int main() {
int *whatever = NULL;
count = readData(whatever);
cout << "Raw array data:" << endl;
writeToConsole(whatever, capacity);
cout << "After simple bubble sort:" << endl;
bubble_sort(whatever, capacity, ascending);
writeToConsole(whatever, capacity);
cout << "Now descending:" << endl;
bubble_sort(whatever, capacity, descending);
writeToConsole(whatever, capacity);
return 0;
}
int readData(int *&arr) {
ifstream inputFile;
inputFile.open("data.txt");
if (!inputFile) {
cout << "Error!";
}
inputFile >> capacity;
arr = new int[capacity];
for(int i = 0; i < capacity; i++){
inputFile >> arr[i];
}
inputFile.close();
return capacity;
}
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bsort(int *arr, int last) {
int i, j;
bool swapped;
for (i = 0; i < last + 1; i++)
{
swapped = false;
for (j = 0; j < last-i; j++)
{
if (arr[j] > arr[j+1])
{
swap(arr[j], arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
void writeToConsole(int *arr, int last) {
cout << "[ ";
for(int i = 0; i < last; i++){
cout << arr[i] << " ";
}
cout << "]" << endl;
}
void bubble_sort(int *arr, int last, int(*ptr)(int, int)){
int i, j;
bool swapped;
for (i = 0; i < last; i++)
{
swapped = false;
for (j = 0; j < last-i; j++)
{
//Use the function pointer to determine which logic to use
if (ptr(arr[j] , arr[j+1]))
{
swap(arr[j], arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
int ascending(int a, int b){
return a > b;
}
int descending(int a, int b){
return a < b;
}
My output looks like this:
Raw array data:
[ 8 4 7 2 9 5 6 1 3 ]
After simple bubble sort:
[ 0 1 2 3 4 5 6 7 8 ]
Now descending:
[ 9 8 7 6 5 4 3 2 1 ]
Any ideas as to why my second sort is throwing in a zero? Thank you!
you have to do this change is in bubble_sort function
for (j = 1; j < last - i; j++)
{
//Use the function pointer to determine which logic to use
if (ptr(arr[j-1], arr[j]))
{
swap(arr[j-1], arr[j]);
swapped = true;
}
}
My code works when put in the int main() function but when I implement it as another function (void bubbleSort) the output displays it as if there was no sorting done.
void bubbleSort(int numeros[])
{
int store = 0;
int length = ARRAY_SIZE(numeros);
for(int i=0; i<(length-1); i++)
{
for(int j=0; j<(length-i-1); j++)
{
if(numeros[j] < numeros[j+1])
{
store = numeros[j];
numeros[j] = numeros[j+1];
numeros[j+1] = store;
}
}
}
for(int m=0; m<1000; m++)
{
cout << numeros[m] <<' ';
}
}
What could I have possibly done wrong? Any help would be greatly appreciated.
You can't pass a full array as an argument to a c++ function, only a pointer to the first element in the array. As a result you need some way to tell the function how long the array is. One way it to pass that in as another argument (as shown below). There is some discussion and suggestions of other/better ways to do it here.
For example if you accidentally pass in the wrong length argument to these functions they will start operating on whatever memory exists after the block of memory where your array is.
#include <iostream>
using namespace std;
void printArray(int array[], int length) {
for(int i=0; i<length; i++) {
cout << array[i] << " ";
}
cout << endl;
}
void bubbleSort(int numeros[], int length) {
int store = 0;
for(int i=0; i<(length-1); i++) {
for(int j=0; j<(length-i-1); j++) {
if(numeros[j] < numeros[j+1]) {
store = numeros[j];
numeros[j] = numeros[j+1];
numeros[j+1] = store;
}
}
}
cout << "array at end of bubble sort: ";
printArray(numeros, length);
}
int main() {
int anArray[] = {1, 3, 2, 4, 6, 5, 10, 9, 7, 8};
int arraySize = sizeof(anArray)/sizeof(anArray[0]);
cout << "arraySize: " << arraySize << endl;
cout << "array before sort: ";
printArray(anArray, arraySize);
bubbleSort(anArray, arraySize);
cout << "array after sort: ";
printArray(anArray, arraySize);
return 0;
}
I'm having some problems with this program. It is meant to input random numbers into an array, change its dimensions, sort them, the output the sorted array. For some reason, the array will only fill with one number (-858993460) and I cannot figure out why. Any help would be greatly appreciated.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cstring>
using namespace std;
void InputArray(int[][5], int, int);
void OutputArray(int[], int);
void SelectionSort(int[], int);
void CopyArray(int[][5], int, int, int[], int);
int main()
{
int sample_1[80];
int sample_2[16][5];
InputArray(sample_2, 16, 5);
CopyArray(sample_2, 16, 5, sample_1, 80);
cout << "Before sorting, contents of the array:" << endl << "----------------------" << endl;
OutputArray(sample_1, 80);
SelectionSort(sample_1, 80);
cout << "After sorting, contents of the array:" << endl << "----------------------" << endl;
OutputArray(sample_1, 80);
return 0;
}
//generate random numbers for a two dimensional array
void InputArray(int array[][5], int m, int n)
{
int i, j;
srand(time(NULL));
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
array[i][j] = rand() % 1000;
}
}
}
//display values in a one-dimensional array
void OutputArray(int array[], int number)
{
int i;
for (i = 0; i < number; i++)
{
cout << array[i] << "\t";
}
}
// selection sort of a one-dimensional array
void SelectionSort(int numbers[], int array_size)
{
int i, j, a;
for (i = 0; i < array_size; ++i) {
for (j = i + 1; j < array_size; ++j) {
if (numbers[i] > numbers[j]) {
a = numbers[i];
numbers[i] = numbers[j];
numbers[j] = a;
}
}
}
return;
}
//x and y and two dimensions of array_2d; n is the dimension of array_1d
//copy values from array_2d[][] to array_1d[]
//assume x*y equals n
void CopyArray(int array_2d[][5], int x, int y, int array_1d[], int n)
{
memcpy(array_2d, array_1d, sizeof(array_1d));
return;
}
void CopyArray(int array_2d[][5], int x, int y, int array_1d[], int n)
{
memcpy(array_2d, array_1d, sizeof(array_1d));
}
That's your problem right there. The size of the array_1d is unspecified here. The sizeof() operator does not know the size of the array that's being copied.
In fact, I'm surprised that this even compiles, although I'm too lazy to test it with gcc.
What you need to do is calculate the size of the array yourself, multiply it by sizeof(int), and use that instead of the existing sizeof() operator.
My assignment asks me to write a function that takes an array and the size of that array as a parameter, and to find the mode. If there are multiple modes, I am to find them all, and place them in a vector and print said vector in an ascending order.
For example, if I input the following integers:
3, 4, 2, 1, 2, 3
Then the output should display
2, 3
If I input the following integers:
1, 2, 3, 4
Then the output should display:
1, 2, 3, 4.
However, my program somehow only finds the first mode and displays it in a really awkward manner.
Here was my input:
3, 4, 2, 3, 2, 1
And this was the output:
3
3
3
3
3
Here is my code. Any help would be greatly appreciated. Thank you all for your time!
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int size; //array size
int* array; //array of ints
int arraycount; //counter for array loop
void findMode(int array[], int size); //function prototype
//intialize array
cout << "Enter number of integers ";
cout << "you wish to input." << endl;
cin >> size;
cout << "Enter the integers." << endl;
array = new int[size];
for (arraycount = 0; arraycount < size;
arraycount++)
cin >> array[arraycount];
//call function
findMode(array, size);
return 0;
}
void findMode(int array[], int size) {
int counter = 1;
int max = 0;
int mode = array[0];
int count;
vector <int> results;
//find modes
for(int pass = 0; pass < size - 1; pass++) {
if(array[pass] == array[pass+1]) {
counter++;
if(counter > max) {
max = counter;
mode = array[pass];
}
}
else {
counter = 1;
}
}
//push results to vector
for (count=0; count < size - 1; count++) {
if(counter == max) {
std::cin >> mode;
results.push_back(mode);
}
}
//sort vector and print
std::sort(results.begin(), results.end());
for (count=0; count < size - 1; count++) {
cout << mode << endl;
}
}
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
int main() {
int size; //array size
int* array; //array of ints
std::vector<int> vecInput;
int arraycount; //counter for array loop
void findMode(std::vector<int> vec); //function prototype
//intialize array
cout << "Enter number of integers ";
cout << "you wish to input." << endl;
cin >> size;
cout << "Enter the integers." << endl;
array = new int[size];
for (arraycount = 0; arraycount < size; arraycount++)
{
int num;
cin >> num;
vecInput.push_back(num);
}
//call function
findMode(vecInput);
return 0;
}
void findMode(std::vector<int> vec)
{
std::sort(vec.begin(), vec.end());
std::map<int, int> modMap;
std::vector<int>::iterator iter = vec.begin();
std::vector<int> results;
int prev = *iter;
int maxCount = 1;
modMap.insert(std::pair <int,int>(*iter, 1));
iter++;
for (; iter!= vec.end(); iter++)
{
if (prev == *iter)
{
std::map<int, int>::iterator mapiter = modMap.find(*iter);
if ( mapiter == modMap.end())
{
modMap.insert(std::pair <int,int>(*iter, 1));
}
else
{
mapiter->second++;
if (mapiter->second > maxCount)
{
maxCount = mapiter->second;
}
}
}
else
{
modMap.insert(std::pair <int,int>(*iter, 1));
}
prev = *iter;
}
std::map<int, int>::iterator mapIter = modMap.begin();
for (; mapIter != modMap.end(); mapIter++)
{
if (mapIter->second == maxCount)
{
results.push_back(mapIter->first);
}
}
cout << "mod values are " <<endl;
std::vector<int>::iterator vecIter = results.begin();
for (; vecIter != results.end(); vecIter++)
cout<<*vecIter<<endl;
}
Thank you all for the help, I was able to get the code to work. Turns out the problem was the cin in my vector portion of the function. Here is my revised code:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <stdlib.h>
#include <vector>
using namespace std;
#define N 100
void findMode(int x[], int size); //function prototype
vector<int> results; //vector
int main(void) {
int* x;
int size=0;
int arraycount;
//intialize array
cout << "Enter number of integers ";
cout << "you wish to input." << endl;
cin >> size;
cout << "Enter the integers." << endl;
x = new int[size];
for (arraycount = 0; arraycount < size;
arraycount++)
cin >> x[arraycount];
//send array and size to function
findMode(x, size);
return 0;
}
//findMode function
void findMode(int x[], int size) {
int y[N]={0};
int i, j, k, m, cnt, count, max=0;
int mode_cnt=0;
int num;
int v;
vector<int> results;
vector<int>::iterator pos;
//loop to count an array from left to right
for(k=0; k<size; k++) {
cnt=0;
num=x[k]; //num will equal the value of x[k]
for(i=k; i<size; i++) {
if(num==x[i])
cnt++;
}
y[k]=cnt; //
}
//find highest number in array
for(j=0; j<size; j++) {
if(y[j]>max)
max=y[j];
}
//find how many modes there are
for(m=0; m<size; m++) {
if(max==y[m])
mode_cnt++;
}
//push results to vector
for (m=0; m < size; m++) {
if(max == y[m]) {
//after taking out this line the code works properly
// std::cin >> x[m];
results.push_back(x[m]);
}
}
//sort vector and print
std::sort(results.begin(), results.end());
cout << "The mode(s) is/are: ";
for (pos=results.begin(); pos!=results.end(); ++pos) {
cout << *pos << " ";
}
}
The following code is not working for heap sort. It looks ok to me. Can someone help me please? I have followed the pseudo code from CLRS, the sorted numbers are not being updated after the algorithm is traversed.
#include <iostream>
using namespace std;
void max_heapify(int *b, int i,int he_size)
{
int l,r,largest;
l=2*i;
r=(2*i+1);
if (l<=he_size && b[l]>b[i])
largest=l;
else largest=i;
if (r<=he_size && b[r]> b[largest])
largest=r;
if (largest!=i)
{
swap(b[i],b[largest]);
max_heapify(b,largest,he_size);
}
}
void build_max_heap(int *c,int h_size,int strlength)
{
for (int q=(strlength)/2;q==1;--q)
{
max_heapify(c,q,h_size);
}
}
void swap(int a, int b)
{
int c=b;
b=a;
a=c;
}
int main()
{
int length;
int heap_size;
cout<<"Enter the number of numbers to be sorted by heap sort"<<endl;
cin>>length;
int* a=NULL;
a=new int[length-1];
int temp;
cout<<"Enter the numbers"<<endl;
for(int i=0;i<length;i++)
{
cin>>temp;
*(a+i)=temp;
}
cout<<"The given numbers are:"<<endl;
for(int j=0;j<length;j++)
cout<<*(a+j)<<" "<<endl;
heap_size= length;
build_max_heap(a,heap_size,length);
for (int l=length;l==2;--l)
{
swap(a[1],a[length]);
heap_size=heap_size-1;
max_heapify(a,1,heap_size);
}
cout<<"The sorted numbers are:"<<endl;
for(int j=0;j<length;j++)
cout<<*(a+j)<<" "<<endl;
system("pause");
return 0;
}
The number of mistakes in your code is enormous. Sorry to say it.
void swap(int a, int b)
{
int c=b;
b=a;
a=c;
}
does nothing - a and b should be passed by link, not by value:
void swap(int &a, int &b)
{
int c=b;
b=a;
a=c;
}
for (int q=(strlength)/2;q==1;--q) is wrong. You meant for (int q=(strlength)/2;q>1;--q). Your loop is running only when q==1.
a=new int[length-1]; The size of array should be length, not length-1. And even though swap(a[1],a[length]); is wrong, because a[length] is out of array.
Also there are some mistakes in algorithm. I tried to rewrite as less code as possible.
Right code is:
#include <iostream>
using namespace std;
void sift_down(int *a, int start, int end) {
int root = start;
while (root * 2 + 1 <= end) {
int child = root * 2 + 1;
int sw = root;
if (a[sw] < a[child])
sw = child;
if (child + 1 <= end and a[sw] < a[child + 1])
sw = child + 1;
if (sw == root)
return;
else
swap(a[root], a[sw]);
root = sw;
}
}
void max_heapify(int *b, int count) {
int start = (count - 2) / 2;
while (start >= 0) {
sift_down(b, start, count - 1);
--start;
}
}
void swap(int &a, int &b) {
int c = b;
b = a;
a = c;
}
int main() {
int length;
int heap_size;
cout << "Enter the number of numbers to be sorted by heap sort" << endl;
cin >> length;
int *a = new int[length];
cout << "Enter the numbers" << endl;
for (int i = 0; i < length; i++) {
cin >> a[i];
}
cout << "The given numbers are:" << endl;
for (int j = 0; j < length; j++)
cout << a[j] << " ";
cout << endl;
heap_size = length;
max_heapify(a, heap_size);
--heap_size;
while (heap_size) {
swap(a[heap_size], a[0]);
--heap_size;
sift_down(a, 0, heap_size);
}
cout << "The sorted numbers are:" << endl;
for (int j = 0; j < length; j++)
cout << a[j] << " ";
cout << endl;
//system("pause");
return 0;
}