How do I swap elements in the given code since I get message that expression must a modifiable lvalue?
I need to swap function value and array element in a for loop.
int niz[2] = { 2,1 };
int temp;
for (int i = 0;i < 1;i++)
{
temp = niz[i];
niz[i] = minimum(niz, 2, i);
minimum(niz, 2, i) = temp;
}
for (int i = 0;i < 2;i++)
{
cout << niz[i] << endl;
}
#include <iostream>
using namespace std;
void swap(int arr[], int size);
int main(void) {
int x[2] = {2, 1};
cout << "Before: ";
for (int i = 0; i <= 1; i++) {
cout << x[i] << ", ";
}
swap(x, 2);
cout << endl << "After: ";
for (int i = 0; i <= 1; i++) {
cout << x[i] << ", ";
}
return 0;
}
void swap(int arr[], int size) {
for (int i = 0; i < size / 2; i++) {
arr[i] ^= arr[size - 1 - i];
arr[size - 1 - i] ^= arr[i];
arr[i] ^= arr[size - 1 - i];
}
}
Hope it helps you.
Related
I wanted to write a program to take two arrays as input and convert the first array such that the difference of maximum value and minimum value from the first array gives the smallest possible number.
I tried to write a code to find a smaller number most closest to the maximum from the array in C++, but the function for finding the minimum works on Codelite, but not on other compilers;
Is there any fix to solve this, either to the code or the compiler?
Here is the code I tried:
#include <iostream>
using namespace std;
void swap(int A[], int B[], int n)
{
int x, y, temp;
for(x=0;x<n;++x)
{
for(y=0;y<n;++y)
{
if(A[x]>B[y])
{
temp = A[x];
A[x] = B[y];
B[y] = temp;
}
}
}
}
void sortas(int A[], int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = i; j < n; j++)
{
if (A[i] > A[j+1])
{
temp = A[i];
A[i] = A[j+1];
A[j+1] = temp;
}
}
}
}
int maxfind(int A[], int n)
{
int z, a;
a = A[0];
for(z=0;z<n;++z)
{
if(a<A[z])
{
a = A[z];
}
}
cout << "Max value in A is" << a << endl;
return a;
}
int minfind(int A[], int n, int amax, int amin)
{
int z, maxi;
maxi = amax;
for(z=0;z<n;++z)
{
if(maxi >= A[z])
{
amin = A[z];
}
else
{
maxi = maxi-1;
}
}
cout << "Mix value in A is" << amin << endl;
return amin;
}
int main() {
int z, t;
cout << "Enter number of test cases: ";
cin >> t;
int n, i, j, amax, amin;
for(z=0;z<t;++z)
{
cout << "Enter size of array" << endl;
cin >> n;
int A[n], B[n];
cout << "Enter Array A values:" << endl;
for(i=0;i<n;++i)
{
cin >> A[i];
}
cout << "Enter Array B values:" << endl;
for(j=0;j<n;++j)
{
cin >> B[j];
}
swap(A, B, n);
sortas(A, n);
cout << "Swapped and sorted array is: " << endl;
for(i=0;i<n;++i)
{
cout << A[i] << "\t" << B[i] << endl;
}
amax = 0;
amin = 0;
amax = maxfind(A, n);
amin = minfind(A, n, amax, amin);
}
return 0;
}
Here is the output to that code:
1 1 1 3 4 2
Max value in A is 1 Min value in A is 1
1 2 2
-1882830412 4 3 6 3
Max value in A is 2 Min value in A is -1882830412
The problem is with your bubble sort:
void sortas(int A[], int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = i; j < n; j++) // why not start at i + 1 ??
{
if (A[i] > A[j+1]) // j + 1 is out of bounds when j == n - 1
{
temp = A[i];
A[i] = A[j+1]; // <-- Some random value is written to A.
A[j+1] = temp; // <-- Overwriting some variable on the stack
// of main() (possibly B ?)
}
}
}
}
A correct bubble sort (this is not the pedantic bubble sort), this is probably the most used.
void sortas(int A[], int n)
{
for (int i = 0; i < n - 1; ++i)
{
for (int j = i + 1; j < n; ++j)
{
if (A[i] > A[j])
std::swap(A[i], A[j]);
}
}
}
The actual bubble sort algorithn (the "pedantic" bubble sort), swaps only occur on neighboring values.
void sortas(int A[], int n)
{
for (int i = 0; i < n - 1; ++i)
{
for (int j = 0; j < (n - i) - 1; ++j)
{
if (A[j] > A[j + 1])
std::swap(A[j], A[j + 1]);
}
}
}
Use one or the other, for integers, the performance is identical.
I am writing a code to sort an array of random integers using four sorting methods bubble, selection, shell and quick sort. I'm using the same code as a rand generator to create random integers which can be sorted by the sort functions. My issue is that when I run multiple sort methods at the same time; my rand generators create the same set of integers for the arrays. How do I fix this so I can have parallel rand generators in the same program? I cannot use c++11 array or STL vector.
main.cpp
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "AssortedSorter.h"
using namespace std;
int main() {
AssortedSorter q, q2;
int UserNumOfNumbers;
int bchoice;
cout << " We pick array size (0) or you pick array size (1): ";
cin >> bchoice;
while (bchoice == 0) {
UserNumOfNumbers = 10000;
int array[UserNumOfNumbers];
srand(std::time(0));
for (int i = 0; i < UserNumOfNumbers; i++) {
array[i] = (rand() %200002) + 1;
}
cout << "\nArray Elements ::" << endl;
for (int i = 0; i < UserNumOfNumbers; i++) {
// long b = array[i];
q.quicksort(array, 0, UserNumOfNumbers);
q.bubbleSort(array, UserNumOfNumbers);
cout << " Number of Elements " << i + 1 << "::" << array[i] << endl;
// q.quicksort(array, 0, UserNumOfNumbers);
}
//q.bubbleSort(array, UserNumOfNumbers);}
// q.selectionSort(array, UserNumOfNumbers);}
return 0;
}
while (bchoice == 1) {
cout << "Enter a number between 10 and 20000: ";
cin >> UserNumOfNumbers;
while (UserNumOfNumbers < 10 || UserNumOfNumbers > 20000) {
cout << "Invalid entry! Please enter a valid value: ";
cin >> UserNumOfNumbers;
}
int array[UserNumOfNumbers];
srand(std::time(0));
for (int i = 0; i < UserNumOfNumbers; i++)
array[i] = (rand() %200002) + 1;
cout << "\nArray Elements ::" << endl;
for (int i = 0; i < UserNumOfNumbers; i++) {
q.bubbleSort(array, UserNumOfNumbers);
cout << " Number of Elements " << i + 1 << "::" << array[i] <</*(rand() %200002) + 1 */endl;
}
int arra[UserNumOfNumbers];
srand(std::time(NULL));
for (int j = 0; j < UserNumOfNumbers; j++)
arra[j] = (rand() %200002) + 1;
cout << "\nArray Elements ::" << endl;
for (int j = 0; j < UserNumOfNumbers; j++) {
q.quicksort(arra, 0, UserNumOfNumbers);
cout << " Number of Elements " << j + 1 << "::" << arra[j] << endl;
}
/*int arran[UserNumOfNumbers];
srand(std::time(0));
for (int k = 0; k < UserNumOfNumbers; k++)
arran[k] = (rand() %200002) + 1;
cout << "\nArray Elements ::" << endl;
for (int k = 0; k < UserNumOfNumbers; k++) {
q.selectionSort(arran, UserNumOfNumbers);
cout << " Number of Elements " << k + 1 << "::" <<(rand() %200001) + 1 << endl;}*/
break;
}
}
AssortedSorter.cpp
#include <iostream>
#include "AssortedSorter.h"
//long array;
using namespace std;
int AssortedSorter::partition(int array[], int start, int stop){
int up = start, down = stop - 1, part = array[stop];
long loopCountQ, swapCountQ;
if (stop <= start)
return start;
while (true)
{
while (array[up] < part){
/* loopCountQ++;
cout << " Loop Count++: " << loopCountQ << endl;*/
up++;}
while ((part < array[down]) && (up < down)){
/* loopCountQ++;
cout << " Loop Count--: " << loopCountQ << endl;*/
down--;}
if (up >= down)
break;
swap(array[up], array[down]);{
/* swapCountQ++;
cout << " Swap Count: " << swapCountQ << endl;*/
up++;
down--;}
}
swap(array[up], array[stop]);{
/* swapCountQ++;
cout << " Swap Count: " << swapCountQ << endl;*/
return up;}
}
int AssortedSorter ::getquicksort() const {
return *b;
}
void AssortedSorter :: quicksort(int a[], int start, int stop){
int i, s = 0, stack[20001];
// b = a;
//long * array = (a);
stack[s++] = start;
stack[s++] = stop;
while ( s > 0)
{
stop = stack[--s];
start = stack[--s];
if (start >= stop) continue;
i = partition(a, start, stop);
if
(i - start > stop - i)
{
stack[s++] = start; stack[s++] = i - 1;
stack[s++] = i + 1; stack[s++] = stop;
}
else {
stack[s++] = i + 1; stack[s++] = stop;
stack[s++] = start; stack[s++] = i - 1;
}
}
}
void AssortedSorter:: bubbleSort(int array[], int size) {
int maxElement;
int index;
//long loopcount = 0;
for (maxElement = size - 1; maxElement > 0; maxElement--) {
for (index = 0; index < maxElement; index++) {
if (array[index] > array[index + 1]) {/*loopcount++;
cout << " Loop count: " << loopcount << endl;*/
swap(array[index], array[index + 1]);
}
}
}
}
/*void AssortedSorter :: swap(int &a, int &b){
/* long int swapcount = 0;
{swapcount++;
cout << "Swap count: " << swapcount << endl;}
int temp = a;
a = b;
b = temp;
}*/
void AssortedSorter::selectionSort(int array[], int size)
{
int minIndex, minValue;
long int loopcountsel = 0;
for (int start = 0; start < (size - 1); start++)
{
minIndex = start;
minValue = array[start];
for (int index = start + 1; index < size; index++)
{
if(array[index] < minValue)
{
loopcountsel++;
// cout << "Loop count: " << loopcountsel << endl;
}
if(array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
swap(array[minIndex], array[start]);
}
}
void AssortedSorter :: swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
AssortedSorter.h
#ifndef SORTER_ASSORTEDSORTER_H
#define SORTER_ASSORTEDSORTER_H
class AssortedSorter {
public:
void quicksort(int a[], int, int);
int getquicksort() const;
int partition(int [], int, int);
void bubbleSort(int[], int);
int getbubblesort() const;
//void swap(int & , int &);
int getswap() const;
void selectionSort(int[], int);
void swap(int &, int &);
private:
int* b;
};
#endif //SORTER_ASSORTEDSORTER_H
I am having a tough time trying to follow the logic here as to why it is not working correctly
expected output :
1 5 6 8
any help is greatly appreciated
Update: I got selection sort and insertion sort mixed up
OUTPUT:
unaltered array
5 8 1 6
1 -858993460 -858993460 6
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "SelectionSORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "SelectionSORT2\n";
}
cout << "SelectionSORT3\n";
}
#include <iostream>
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
UPDATE
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "Selection SORT1\n";
int I;
for (i = 0; i < n ; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = i;
int j;
for (j = i + 1;j < n ;j++)
{
std::cerr << j << ' ' << firstIndex << '\n';
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
swap(arr[i], arr[firstIndex]);
}
cout << " \n";
}
cout << " \n";
}
#include <iostream>
#include "BubbleSort.h"
#include "InsertionSort.h"
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
unaltered array
5 8 1 6
SelectionSORT1
1 0
2 0
3 2
2 1
3 2
3 2
5 6 1 8
You are using the selection sort method not the insertion sort method.
Bit in any case the function is incorrect
void InsertionSort(int *arr,int n)
{
cout << "INSERTION SORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "INSERTION SORT2\n";
}
cout << "INSERTION SORT3\n";
}
For starters it will not sort an array that has two elements due to this for loop
for (i = 0; i < n - 2; i++) //-1 ||-2//
Secondly, the variable firstIndex is not initialized by a value of the index i
firstIndex = arr[i];
So the condition in this if statement
if (arr[j] < arr[firstIndex])
does not make a sense.
Thirdly this inner for loop
for (j = i + 1;j < n - 1;j++)
ignores the last element of the array.
Fourth, this unconditional call of the function swap within the inner for loop
swap(arr[i], arr[firstIndex])
also does not make a sense.
The function can look the following way
void SelectionSort( int a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
size_t min = i;
for ( size_t j = i + 1; j < n; j++ )
{
if ( a[j] < a[min] )
{
min = j;
}
}
if ( min != i ) swap( a[i], a[min] );
}
}
And in main the variable size should have the type size_t - the type of the value of the expression with the operator sizeof
const size_t size = sizeof(array) / sizeof(array[0]);
And instead of the magic number 4 in for loops in main you should use the named constant size or you could use the range-based for loop as
for ( const auto &item : array )
{
cout << item << ' ';
}
cout << endl;
If you indeed mean the insertion sort method then a corresponding function can look for example the following way
void InsertionSort( int a[], size_t n )
{
for (size_t i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
int tmp = a[i];
size_t j = i;
for ( ; j != 0 && tmp < a[j - 1]; --j )
{
a[j] = a[j - 1];
}
a[j] = tmp;
}
}
}
Thank you all for your help
I got it to work like this
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void InsertionSort(int arr[],int n)
{
int i;
for (i = 0; i < n ; i++)
{
int firstIndex,j;
firstIndex = i;
for (j = i + 1;j < n ;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
}
swap(arr[i], arr[firstIndex]);
}
}
The following is C++:
std::set<int> sorted_array({ 5,8,1,6 });
If you have duplicates and need to keep them, use:
std::multiset<int> sorted_array({ 5,8,1,6 });
Done. One line.
I need to write a program which displays the elements of a matrix in a spiral way.My program does not work fine.Here's the code:
#include <iostream>
using namespace std;
void citireMatrice(int a[100][100], int n) // function to read a matrix
{
int i, j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
{
cout<<"a[" << i << "][" << j << "]=";
cin >> a[i][j];
}
}
}
void spiral(int a[100][100], int n)
{
int i, j, k;
if (n % 2==0)
{
k = n / 2;
}
else
{
k = n / 2 + 1;
}
for (i = 1; i <= k; ++i)
{
for (j = 1; j <= n - i + 1; ++j)
{
cout << a[i][j] << " ";
}
for (j = i + 1; j <= n - i + 1; ++j)
{
cout << a[j][n - i + 1] << " ";
}
for (j = n-i; j >= i; j--)
{
cout << a[n - i + 1][j] << " ";
}
for (j = n-1;j>=i+1;j--)
{
cout << a[j][i];
}
}
}
int main()
{
int a[100][100];
int n;
cout << "n=";
cin >> n;
citireMatrice(a, n);
spiral(a, n);
return 0;
}
If I enter n=2 with the elements 1, 2, 3, 4 it displays 4 -858993460 and other numbers like this.Where's my mistake?
You're properly using zero based indexing of arrays in citireMatrice but in spiral you're using one based indexing.
You need to start your loops at 0, and end at < n. (Consider what element of a will be first to be printed out.)
I am trying to learn C++, arrays and pointers. I decided to implement the insertion sort algorithm. So, here is my code and my wrong output. What should I do to correct it? Can you please tell me what is my mistake and what should I avoid if it is a common error?
My code:
// InsertionSort.cpp
#include "stdafx.h"
#include <iostream>
int DeclareAnInteger();
int* DeclareAndShowTheArray(int n);
int* InsertionSort(int *A, int n);
int main()
{
int n = DeclareAnInteger();
int *A;
A = DeclareAndShowTheArray(n);
int *B;
B = InsertionSort(A, n);
system("PAUSE");
return 0;
}
int DeclareAnInteger()
{
int n;
std::cout << "Please enter a positive integer n: ";
std::cin >> n;
return n;
}
int* DeclareAndShowTheArray(int n)
{
int *A;
A = (int *)alloca(sizeof(int) * n);
for (int i = 0; i < n; i++)
{
std::cout << "Please enter the value of A[" << i + 1 << "]: ";
std::cin >> A[i];
}
std::cout << "The unsorted array is: ";
for (int i = 0; i < n; i++)
{
std::cout << A[i];
std::cout << "\t";
}
std::cout << "\n";
return A;
}
int* InsertionSort(int *A, int n)
{
int k;
//int *A = new int[n];
for (k = 1; k < n; k++)
{
int key = A[k];
int m = k - 1;
while (m >= 0 & A[m] > key)
{
A[m + 1] = A[m];
m = m - 1;
}
A[m + 1] = key;
}
std::cout << "The sorted array is: ";
for (int i = 0; i < n; i++)
{
std::cout << A[i];
std::cout << "\t";
}
std::cout << "\n" << std::endl;
return A;
}
My output:
This here is a big problem:
A = (int *)alloca(sizeof(int) * n);
The alloca function allocates on the stack, and it will be lost when the function returns which gives you a stray pointer and undefined behavior when you dereference this pointer.
If you're programming C++ then use new, if you program C then use malloc.