I have the following code.. The method should work but I'm having trouble passing the vector to a function. I searched around and found that vector can be passed as 'references' or 'values' and I tried both, but they didn't seem to work. Am I calling the method incorrectly or passing the vector in a wrong way? Either ways, what can I do to fix this? Thanks! :)
//insertion sort method
#include <iostream>
#include <vector>
using namespace std;
void insertionSort(int arr[], int n){
for(int i = 0; i < n; i++){
int temp = arr[i]; // element adjacent to left sorted array
int j = i - 1;
while(temp > arr[j] && j != 0){
arr[j] = arr[j - 1];
j--;
}
arr[j] = temp;
}
}
int main(){
int n, temp;
cin >> n;
vector <int> arr;
for(int i = 0; i < n; i++){
cin >> temp;
arr.push_back(temp);
}
insertionSort(arr, n);
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
The first parameter of the insertionSort(int arr[], int n) method is wrong.
You also processed the arr incorrectly. At first iteration, int j = 0 - 1 = -1; which is unexpected/ out of bound.
Please try this :
void insertionSort(vector <int> &arr, int n){
int i, j, temp;
for (i = 1; i < n; i++)
{
temp = arr[i];
j = i - 1;
while ((j >= 0) && (temp<arr[j]))
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = temp;
}
}
Thanks !!!
Related
In the function insertionSort, I have defined a variable temp which is equivalent to arr[i]. For the following while loop I have written some conditions one of them is temp < arr[j]), this code works perfectly fine. BUT if I replace this temp with arr[i] in the condition [ i.e while(j >= 0 && arr[i] < arr[j]) ] this code does work as intended. Why is this happening aren't the values of the variable temp and arr[i] the same, as is defined 2 lines above it ?
With while(j >= 0 && arr[i] < arr[j]), it does not work.With while(j >= 0 && temp < arr[j]), it works.
#include<iostream>
void printSortedArray(int arr[], int size){
std::cout<<"{ ";
for(int m=0; m<size-1; ++m){
std::cout<<arr[m]<<", ";
}
std::cout<<arr[size-1]<<" ";
std::cout<<"}";
}
void insertionSort(int arr[], int size){
for(int i=1; i<size; ++i){
int temp = arr[i]; // <---- Variable *temp* ----
int j = i - 1;
while(j >= 0 && temp < arr[j]){ // <---- *while loop*----
arr[j+1] = arr[j];
--j;
}
arr[j+1] = temp;
}
printSortedArray(arr, size);
}
int main(){
int n; std::cout<<"Enter the size of array : ";
std::cin>>n;
int arr[n];
for(int i=0; i<n; ++i){
std::cout<<"Enter the element at index ~ "<<i<<" : ";
std::cin>>arr[i];
}
insertionSort(arr, n);
}
The loop condition should be while (j > 0 && temp < arr[j])
and
the end arr[j] = temp; instead of arr[j+1] = temp;
int arr[] = {7,4,10,8,3,1};
int size = sizeof(arr) / sizeof(arr[0]);
for(int i = 0; i<size-1; i++){
int temp = arr[i];
for(int j = i+1; j < size; j++){
if(arr[j] < temp){
temp = arr[j];
}
}
swap(temp, arr[i]);
}
I am trying to apply the selection sort algorithm on the given array, but the output I am getting is only [1,1,1,1,1,1], I am finding the minimum element through the inner loop, Ican't figure out what is going wrong?
Slightly modified your code;
You need to pass reference(address) to both elements to take place of swapping contents
int arr[] = { 7, 1, 10, 8, 3, 11, 0, 12, 5, 8 };
int size = sizeof(arr) / sizeof(arr[0]);
for(int i = 0; i < size; i++)
{
auto temp = std::min_element( arr + i, arr + size );
std::swap( arr[i], *temp );
}
You have to add algorithm header to use std::min_element
int arr[] = {7,4,10,8,3,1};
int size = sizeof(arr) / sizeof(arr[0]);
for(int i = 0; i<size-1; i++){
int temp = arr[i];
int pos = i;
for(int j = i+1; j < size; j++){
if(arr[j] < temp){
temp = arr[j];
pos = j;
}
}
if(pos != i)
std::swap(arr[pos], arr[i]);
}
This should work.
It is suggested not to use using namespace std;. There is a plethora of reasons why you should not; that I will not mention.
By the way I tried to keep some of your variables the same but to be honest, I didn't. It is better to create variable names that explain what the code is doing. It makes your code a lot more legible and readable.
So opt out of one letter variables. It is fine in for loops, however this is a special case.
Now, here is another alternative suggested by #user4581301 & #Swift -Friday Pie. This method is using std::size using c++17.
For example:
#include <iostream>
#include <utility> // to use the swap() function.
#include <iterator> // to use std::size() function.
int main()
{
int arr[] = { 7,4,10,8,3,1 };
// This --> int size = sizeof(arr) / sizeof(arr[0]); is archaic.
const int length = static_cast<int>(std::size(arr)); // Call this something other than "size"; you can run into issues.
// We use static_cast<int> as a implicit conversion, and the obvious std::size(arr)).
// Going through the elements
for (int StartOfIndex = 0; StartOfIndex < length - 1; ++StartOfIndex)
{
// smallest is the index of the smallest element we’ve encountered this iteration
int smallest = StartOfIndex;
// Looking for a smaller element..
for (int current = StartOfIndex + 1; current < length; ++current)
{
// if we found an element smaller than our last; take note.
if (arr[current] < arr[smallest])
smallest = current;
}
// swap StartOfIndex with smallest.
std::swap(arr[StartOfIndex], arr[smallest]);
}
//Prints array.
for (int index = 0; index < length; ++index)
std::cout << arr[index] << " ";
std::cout << "\n";
return 0;
}
Output: 1 3 4 7 8 10
The first mistake you made in writing for loop's condition, don't use swap(temp, array[i]); yet try to get the basics first.
#include <iostream>
using namespace std;
int findsmall(int arr[], int i, int size){
int s, pos, j;
s = arr[i];
pos = i;
for(j = i+1; j < size; j++){
if(arr[j] < s){
s = arr[j];
pos = j;
}
}
return pos;
}
int main() {
int arr[] = {7,4,10,8,3,1};
int size = sizeof(arr) / sizeof(arr[0]);
int smallnum;
int temp;
int count = 0;
cout << "Original array: ";
for(int i = 0; i < size; i++){
if(i < size - 1){
cout << arr[i] << ", ";}
else{
cout << arr[i];
}
}
cout << endl;
for(int i = 0; i < size; i++){
smallnum = findsmall(arr,i, size);
temp = arr[i];
arr[i] = arr[smallnum];
arr[smallnum] = temp;
count++;
}
cout << "Sorted array: ";
for(int i = 0; i < size; i++){
if(i < size - 1){
cout << arr[i] << ", ";}
else{
cout << arr[i];
}
}
cout << endl;
return 0;
}
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
swap(&arr[min_idx], &arr[i]);
}
}
selectionSort(arr,size);
This should work.
After taking the input for variable k,its value is automatically changing to 5.
#include<iostream>
using namespace std;
int search(int arr[], int target, int size) {
int l = 0; int mid;
while(l <= size) {
mid = l + (size-l) / 2;
if(arr[mid] == target)
return 1;
if(arr[mid] > target)
size = mid - 1;
if(arr[mid] < target)
l = mid + 1;
}
return 0;
}
int sort(int arr[], int size) {
int temp; bool swap = false;
for(int i = 0; i < size; i++) {
bool swap = false;
for(int j = 0; j < size - i; j++) {
if(arr[j] > arr[j + 1]) {
temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
swap = true;
}
}
if(swap == false)
break;
}
return 0;
}
int main() {
int n, k;
int count;
int j;
int arr[n];
cin >> n;
cin >> k;
int value;
for(int i = 0; i < n; i++)
cin >> arr[i];
sort(arr, n - 1);
for(int i = 0; i < n; i++) {
value=arr[i] + k;
j = search(arr, value, n - 1);
if(j == 1)
count++;
}
cout << count;
}
I printed the value of k just after the input and it shows the correct value. but inside the main function when i am using it to calculate the variable "value" its value is being taken as 5.Something is happening before the sort function is being called.
I'm writing a program for my C++ class that takes the user input for the size of a int and char array, fills the arrays with random values (numbers 0-100, letters A-Z) then sorts, reverses, and displays both arrays.
For the most part the program works and I understand the logic I used here, but...
After running and debugging the code multiple times. I noticed that when the arrays were being filled with values, the first element, even though it was actually being given a value, it would not print the assigned value it was given in ascending order, but would in a descending order? I don't understand this at all.
NOTE: I have to use template functions for the sorting, reversing and display of the arrays.
template <class T>
void sort(T *arr, int a) {
T temp;
for (int i = 0; i < a; i++) {
for (int j = a; j > 0; j--) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
template <class T>
void reverse(T *arr, int a) {
T temp;
for (int i = 0; i < a / 2; i++) {
temp = arr[i];
arr[i] = arr[a - i];
arr[a - i] = temp;
}
}
template <class T>
void display(T *arr, int a) {
for (int i = 0; i < a; i++) {
cout << arr[i] << ", ";
}
cout << endl;
}
template<class T>
void save(T *arr, int a) {
sort(arr, a);
display(arr, a);
reverse(arr, a);
display(arr, a);
}
int main() {
int x, y;
cout << "Please enter a number for an array of data type \"int\"" << endl;
cin >> x;
cout << "Please enter a number for an array of data type \"char\"" << endl;
cin >> y;
int *arr1 = new int[x];
char *arr2 = new char[y];
for (int i = 0; i < x; i++)
cout << (arr1[i] = rand() % 100 + 1);
srand(time(nullptr));
for (int i = 0; i < y; i++)
cout << (arr2[i] = rand() % 26 + 65);
system("cls");
save(arr1, x);
save(arr2, y);
delete[]arr1;
delete[]arr2;
system("pause");
return 0;
}
You are using the complete length here:
save(arr1, x);
save(arr2, y);
So in reverse
arr[i] = arr[a - i];
arr[a - i] = temp;
you need to -1 on the length or you'll get an invalid index when i == 0
arr[i] = arr[a - 1 - i];
arr[a - 1 - i] = temp;
Like R Sahu says, in sort
for (int j = a; j > 0; j--) {
you need to -1 because a is the length which will be an invalid index.
for (int j = a-1; j > 0; j--) {
As a side note, you can declare Temp t inside of the for loop in reverse and inside of the if in sort because it is only used in those scopes.
EDIT:
Also I overlooked, in sort you need to change
j>0
to
j >= 0
that way you access the first element of the array as well.
You have a off-be-one error in couple of places.
for (int j = a; j > 0; j--) {
is incorrect. a is an invalid index for the array. Change that line to use j = a-1:
for (int j = a-1; j > 0; j--) {
You have a similar, off-by-one, error in reverse. Instead of
arr[i] = arr[a - i];
arr[a - i] = temp;
you need to use:
arr[i] = arr[a - i - 1];
arr[a - i - 1] = temp;
Your implementation of sort is not correct. I don't want to get into the algorithmic details here but changing the order of the values used for j seems to fix the problem.
for (int i = 0; i < a; i++) {
for (int j = i+1 ; j < a ; j++) {
// The swapping code.
}
}
You are using bubble sort that is O(n^2) time complexity. Consider using faster algorithm. If you don't want to implement it on your own, use sort() function. It's complexity is about O(n log n), which is very good.
http://www.cplusplus.com/reference/algorithm/sort/
#include <iostream>
#include <algorithm>
using namespace std;
bool comp(int i1, int i2) { // comp function is to compare two integers
return i1 < i2;
}
int main() {
int x[30];
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x[i];
}
sort(x, x + n, comp); // if you don't provide comp function ( sort(x, x+n) ), sort() function will use '<' operator
for (int i = 0; i < n; i++) {
cout << x[i] << " ";
}
return 0;
}
I am using an insertion sort function to sort a 5000 int ascending array. when i pass the array's address to the function call, i get [Error] name lookup of 'i' changed for ISO 'for' scoping [-fpermissive]. Maybe I should use a vector but I am unfamiliar with them. Maybe I coded something wrong?
#include <iostream>
#define SIZE 5000 //array size
using namespace std;
void insertionSort(int arr[], int length) {
int i, j, tmp;
for (i = 1; i < length; i++) {
j = i;
while (j > 0 && arr[j - 1] > arr[j]) {
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
j--;
}
}
}
int main() {
int a[SIZE];
int count = 1;
for(int i=0; i<SIZE; i++) {
a[i] = count;
count++;
}
for(int i = 0; i < SIZE; i++) {
printf("%d\t", a[i]);
}
insertionSort(&a[i], SIZE);
}
You probably want to call
insertionSort(a, SIZE)
// insertionSort(&a[i], SIZE); Here you haven't declared i in funciton main(), only in your for loop. And the call to insertionSort is outside of your loop.
Passing (&a)[0] and a mean the same thing.