c++
When printing to console, if function execution is sequential it would seem logical the ordered array would be printed after calling insertionSort, however order list does not print until next loop. Any help would be appreciated.
#include <stdio.h>
#include <iostream>
#include <array>
using namespace std;
void insertionSort(int* array, int size) {
for (int i = 1; i < size; i++) {
int key = i - 1;
while (i > 0 && array[key] > array[i] ) {
int tmp = array[i];
array[i] = array[key];
array[key] = tmp;
i -= 1;
key -= 1;
}
}
}
const int ARRAY_MAXSIZE = 5;
int main(void) {
int *array = (int*)calloc(ARRAY_MAXSIZE, sizeof(int));
int input;
cout << "Enter 5 digits\n";
for (int size=0; size < ARRAY_MAXSIZE; size++) {
cout << size << " index ";
cin >> input;
array[size] = input;
insertionSort(array, size);
for (int j=0; j <= size; j++) {
cout << array[j];
}
cout << '\n';
}
}
Console Entry
This is a classic off-by-one error. Your insertionSort expects you to pass the number of elements to sort via the parameter size. But your main loop is always holding a value that is one less than the size immediately after adding an element.
I want to say that bugs like this are easily discovered by stepping through your program's execution with a debugger. If you don't know how to use a debugger, start learning now. It is one of the most important tools used by developers.
Anyway, the quick fix is to change your function call to:
insertionSort(array, size + 1);
However, as Paul McKenzie pointed out in comments, it's a bit crazy to do this every time you add a new element because your function sorts an entire unsorted array. Your array is always nearly sorted except for the last element. You only need to call that function once after your input loop is done:
// Read unsorted data
for (int size = 0; size < ARRAY_MAXSIZE; size++) {
cout << size << " index ";
cin >> input;
array[size] = input;
}
// Sort everything
insertionSort(array, ARRAY_MAXSIZE);
// Output
for (int j = 0; j < ARRAY_MAXSIZE; j++) {
cout << array[j];
}
cout << '\n';
But if you want every insertion to result in a sorted array, you can "slide" each new value into place after inserting it. It's similar to a single iteration of your insertion-sort:
// Sort the last element into the correct position
for (int i = size; i >= 1 && array[i] > array[i - 1]; i--)
{
std::swap(array[i], array[i - 1]);
}
Even better, you don't need to swap all those values. You simply read the value, then shuffle the array contents over to make room, then stick it in the right spot:
// Read next value
cin >> input;
// Shuffle elements to make room for new value
int newPos = size;
while (newPos > 0 && array[newPos - 1] > input) {
array[newPos] - array[newPos - 1];
newPos--;
}
// Add the new value
array[newPos] = input;
Related
I have a program I am writing that prints out a Fibonacci Sequence up to 30 numbers. I must do this by traversing the array using pointers, but I don't know how to.
There is not a lot of easy to follow information that I can understand.
When I see the code for c++ answers to this, all I see is this...
I'm a noob and I am having a hard time looking at all of the 'std::' conventions when I have to look at code. I know it's probably good convention, but I am not good with it yet. So I would like a straightforward example, assuming I am using the using namespace std; line of code within my project.
I have tried setting the for..loop up with the pointer variable but I am not sure how to do this.
void fibonacciSequence(){
//initialize the array and users input
const int ARRAY_SIZE = 30;
int numbers[ARRAY_SIZE];
int *pointer;
pointer = numbers;
//Traverse the array and generate the Fibonacci Sequence
for(int i = 0; i < ARRAY_SIZE; i++){
//Set first element to 0
if(i == 0){
numbers[i] = 0;
}
//Set second element to 1
else if (i == 1){
numbers[i] = 1;
}
//Start calculating the sequence after the first 2 elements
//have been established.
else{
numbers[i] = numbers[(i - 1)] + numbers[(i - 2)];
}
}
// Output the Fibonacci Sequence after calculations.
for(int i = 0; i < ARRAY_SIZE; i++){
cout << numbers[i] << endl;
}
}
This code I have works perfectly. But instead of traversing the array using 'i' in the for...loop, i need to use 'pointer.'
It's actually very simple change this
for(int i = 0; i < ARRAY_SIZE; i++){
cout << numbers[i] << endl;
}
to this
for(int* p = numbers; p < numbers + ARRAY_SIZE; p++){
cout << *p << endl;
}
Explanation
int* p = numbers - set p to point to the beginning of the array
p < numbers + ARRAY_SIZE - check p hasn't reached the end of the array
p++ - move p on to the next element of the array
*p - access the element that p is pointing to
Similar changes to your first loop.
This whole topic is pointer arithmetic, maybe you could do some research.
This probably isn't a good project for learning pointers, since indexing is the most natural way of computing a fibanocci sequence. But here goes. Replace that generator loop with this:
int *current = numbers;
*current++ = 0;
*current++ = 1;
while (current != numbers + ARRAY_SIZE) {
*current = *(current - 1) + *(current - 2);
++current;
}
And then for the output:
for (current = numbers; current != numbers + ARRAY_SIZE; ++current)
std::cout << *current << '\n';
as the title says I'm attempting to compare elements in an array. My intent is to have the user enter 3 integers into the program, thereafter it should increment through this array comparing the the 1st number to the 2nd, and so forth and swapping the element's from order of lowest to highest.
My issue currently is that it will swap the first and second elements but the third causes an integer overflow due to me comparing and assigning an integer in an index higher than the initialized array can hold.
I'm currently drawing a blank as to how I could still compare these numbers in this manner without causing it to overflow.
A hint or perhaps a whole different perspective would be appreciated.
#include "E:/My Documents/Visual Studio 2017/std_lib_facilities.h"
int main()
{
cout << "Enter three integers: \n";
int numbersArray[3];
int temp = 0; //This lets us hold our integers temporarily so we can swap them around in the array
//This enters integers as elements in the array
for (int i = 0; i < 3; i++)
{
cin >> numbersArray[i];
}
//This should swap the elements from smallest to greatest
for (int i = 0; i = 3; i++)
{
if (numbersArray[i] > numbersArray[i+1])
temp = numbersArray[i];
numbersArray[i] = numbersArray[i+1];
numbersArray[i+1] = temp;
//swap(numbersArray[i], numbersArray[++i]);
}
//This prints the index's containing the elements in the array
for (int i = 0; i < 3; i++)
{
cout << numbersArray[i] << ' ';
}
cout << endl;
keep_window_open();
return 0;
}
You will need to modify this to suit your needs, but this should get you on the right track. One important thing to investigate is how you decided to sort the elements. Your sorting needs to be looped, otherwise, you won't necessarily sort the entire array (depending on your inputs).
#include <iostream>
using namespace std;
int main()
{
cout << "Enter three integers: \n";
int numbersArray[3];
int temp = 0; //This lets us hold our integers temporarily so we can swap them around in the array
//This enters integers as elements in the array
for (int i = 0; i < 3; i++)
{
cin >> numbersArray[i];
}
for(int loop = 0; loop <3; loop++){
//This should swap the elements from smallest to greatest
for (int i = 0; i < 2; i++)
{
if (numbersArray[i] > numbersArray[i+1]){
temp = numbersArray[i];
numbersArray[i] = numbersArray[i+1];
numbersArray[i+1] = temp;
}
//swap(numbersArray[i], numbersArray[++i]);
}
}
//This prints the index's containing the elements in the array
for (int i = 0; i < 3; i++)
{
cout << numbersArray[i] << ' ';
}
cout << endl;
return 0;
}
I am attempting to fill an array backwards from 20 to 0 but whenever I print it out it still prints out forwards. For instance I want to put in 1,2,3,4,5 and have it come out as 5,4,3,2,1.
I have attempted to do a for loop that counts backwards from 20 to 0 but when i print it it is still coming out incorrect. Any help?
int temp;
for (int i = 20; i > 0; i--)
{
cout << "Please enter the next number. Use a -1 to indicate you are done: ";
cin >> temp;
while(temp > 9 || temp < -2)
{
cout << "You may only put numbers in 0 - 9 or -1 to exit. Please enter another number: ";
cin >> temp;
}
arr1[i] = temp;
cout << arr1[i];
}
for (int i = 21; i > 0; i--)
{
cout << arr1[i];
What's the size of your array?
Assume that the size is 21 (indexes from 0 to 20).
First of all please note that your first loop will never populate the array at index 0 (something like this arr1[0] = temp will never be executed inside your first loop).
If you want to avoid this behavior you should write your first for loop like this:
for (int i = 20; i >= 0; i--){...}.
The second for loop has some issues:
You are traversing the array backwards while you want to do the opposite.
The loop starts from an index out of bound (21).
The loop may print some undefined values (You should remember the index of the last added value).
I suggest you to use other data structures like a Stack but if you want to use an array you can edit your code as follows:
int i;
for (i = 20; i >= 0; i--){...}
for (i; i <= 20; ++i) { cout << arr1[i]; }
If you don't want to declare int i; outside of the loop you can do something like that:
int lastAdded;
for (int i = 20; i >= 0; i--){
...
lastAdded = i;
}
for (int i = lastAdded; i <= 20; i++) { cout << arr1[i]; }
Edit: Note that neither your code nor mine stops asking for a new value after the insertion of a -1.
If you want to achieve this behavior you should use a while loop instead of the first for loop and check for the exit condition.
Disclaimer: I know that parallel arrays are awful and should be avoided and that selection sort is not the most efficient sort, but in this case that's the way the boss man wants it done. I have looked at a lot of different websites and none that really seem to nail down an answer. Also, it is probably good to point out that I am new to C++ and only know fairly basic coding and debugging.
I have two simple parallel arrays and am trying to design a simple selection sort that sorts one of the arrays, and then swaps the elements in the second array accordingly. I have the selection sort part working, but it does not seem to swap the elements in my second array correctly.
Here is what my output looks like:
1 (jibberish)
2 (jibberish)
3 (jibberish)
4 (jibberish)
5 (jibberish)
Where I have (jibberish) the console does not form any identifiable letter, just odd shapes (if it's helpful, the last element that is output is a heart).
Here's what it is supposed to look like:
1 a
2 b
3 c
4 d
5 e
Now I realize that I could easily run a selection sort on the second array in this scenario, but my point is to get the second array to swap elements respective to what the selection sort does to the first array.
Is there any way to keep these arrays lined up correctly? I've been trying to solve this issue for most of the day and I'm sure it's a fairly simple thing to figure out, but my brain is shot.
Below is my code, thanks in advance for looking at it.
#include "stdafx.h"
#include <iostream>
using namespace std;
//Function Prototypes
void sort(int num[], char alph[], int size);
//Selection sort function
void sort(int num[], char alph[], int size)
{
int startScan;
int minIndex;
int minValue;
for (startScan = 0; startScan < (size - 1); startScan++) //Moves through the elements
{
minIndex = startScan;
minValue = num[startScan];
int index = 0;
for (index = startScan + 1; index < size; index++) //Compares the elements
{
if (num[index] < minValue)
{
minValue = num[index];
minIndex = index;
}
}
num[minIndex] = num[startScan];
num[startScan] = minValue;
alph[minIndex] = alph[startScan];
alph[startScan] = alph[index];
}
}
//Main
int _tmain(int argc, _TCHAR* argv[])
{
int num[] = {5, 3, 1, 4, 2};
char alph[] = { 'e', 'c', 'a', 'd', 'b' };
int const SIZE = 5;
//Prints out unsorted array
cout << "This is the unsorted arrays." << endl;
cout << endl;
for (int count = 0; count < SIZE; count++)
{
cout << num[count] << " \t ";
cout << alph[count] << endl;
}
cout << endl;
cout << endl;
//Calls the sort function
sort(num, alph, SIZE);
//Prints out the sorted array
cout << "This is the sorted array." << endl;
cout << endl;
for (int count = 0; count < SIZE; count++)
{
cout << num[count] << " \t";
cout << alph[count] << endl;
}
//Pause
char temp[50];
cin >> temp;
return 0;
}
EDIT: I edited the
alph[minIndex] = num[startScan]
issue so it reads correctly now as:
alph[minIndex] = alph[startScan]
I am now getting this as an output:
1 (jibberish)
2 (jibberish)
3 (jibberish)
4 (jibberish)
5 e
EDIT 2: I edited the line of code under my previous edit and the arrays are now lining up properly and I am no longer getting a bunch of jibberish for outputs. Below is the edited sort function of my code:
//NOTICE temp VARIABLE CHANGES!
void sort(int num[], char alph[], int size)
{
int startScan;
int minIndex;
int minValue;
int temp;
for (startScan = 0; startScan < (size - 1); startScan++) //Moves through the elements
{
minIndex = startScan;
minValue = num[startScan];
temp = alph[startScan];
int index = 0;
for (index = startScan + 1; index < size; index++) //Compares the elements
{
if (num[index] < minValue)
{
minValue = num[index];
minIndex = index;
temp = alph[index];
}
}
num[minIndex] = num[startScan];
num[startScan] = minValue;
alph[minIndex] = alph[startScan];
alph[startScan] = temp;
}
}
The best solution might be to change your
num[minIndex] = num[startScan];
num[startScan] = minValue;
char temp=alph[minIndex];
alph[minIndex] = alph[startScan];
alph[startScan] = temp;
to this which does the job and really can't be made any simpler.
std::swap(num[minIndex], num[startScan]);
std::swap(alph[minIndex],alph[startScan]);
See this line:
alph[minIndex] = num[startScan];
Second faulty line:
alph[startScan] = alph[index];
It should be:
alph[startScan] = alph[minIndex];
By the time the code exits of the inner loop, size has a value of one beyond the array size.
My advice: Use an IDE and the debugger to follow up code execution and examine variables. Also, my first hint should have gotten you looking at incorrect indexes. C++ does not care to check array bounds by default. You usually get garbage when getting out of bounds or following a incorrect pointer. You can remedy the first problem by selecting a compiler option to check for array bounds. That will slow down your application during development time but can be removed once everything works correctly.
I was just practising a little bit and tried to sort an array with the bubble sort algorithm.
Compiler didn't give me any warnings nor errors and it worked well! First you type 10 times a number and then the program sorts them + prints them.
Code:
#include <iostream>
using namespace std;
void arr_sort(int* array, const int arr_size){
int temp = 0; //Temporary integer to store (if necessary) the current element
int end = 0; //Run time condition
while(end++ != arr_size){ // Will loop max. 10 times
for(int i = 0; i < arr_size; i++){
if(array[i] > array[i + 1]){ //If the current element
temp = array[i]; //is bigger than the next
array[i] = array[i + 1];//Change the positions
array[i + 1] = temp;
}
}
}
}
int main(){
int arr_input[10];
for(int i = 0; i < 10;i++) //The user has to type 10 numbers
cin >> arr_input[i]; //which will be stored in this array
arr_sort(arr_input, 10); //sorts the array
cout << endl << endl;
for(int i = 0; i < 10; i++) //Print out the array!
cout << arr_input[i] << ", ";
cout << endl;
return 0;
}
My only problem is the while-loop in the arr_sort function. I mean it sorts the array until end has the same value as arr_size. But often it doesn't need that long. My question now... How can I improve this function? How can I test if the array is completely sorted so the while-loop can stop without running another time and another time ...?
Before your for loop, assume it's sorted:
bool sorted = true;
In your if statement`, record that it's not sorted:
sorted = false;
After your for loop`, return if there was no evidence that it's not sorted:
if ( sorted ) return;
Just outside of the for loop, place a bool and set it to false. Inside the swap block, set the bool to true. After the for loop, check the value of the boolean, and if it's still false, no swaps were made so the array is sorted, so break out of the while loop.
while(end++ != arr_size){ // Will loop max. 10 times
bool swapped = false;
for(int i = 0; i < arr_size; i++){
if(array[i] > array[i + 1]){ //If the current element
temp = array[i]; //is bigger than the next
array[i] = array[i + 1];//Change the positions
array[i + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
}