Sorting an array from Largest to smallest in C++ - c++

I wanna sort an array from largest to smallest number and make a new array which has it sorted...
so here is my code:
#include <iostream>
using namespace std;
int main()
{
int size, sum = 0, answer = 0,pos, max;
int array[size];
int array2[size];
cin >> size;
for (int i = 0; i < size; i++)
{
cin >> array[i];
sum+=array[i];
}
for (int i = 0; i < size; i++)
{
max = 0;
pos = 0;
for (int q = 0; q < size; q++)
{
if (array[q] > max)
{
max = array[q];
pos = q;
}
}
array2[i] = max;
array[pos] = 0;
}
for (int i = 0; i < size; i++)
{
cout << array2[i] << ", ";
}
return 0;
}
When I put my input:
5
1 2 3 4 5
The output I get is:
0, 0, 0, 0, 5,
but I expect it to be 5, 4, 3, 2, 1,

First of all always initialize a variable when you create it as by default it has some garbage value in C++,
Also you are trying to assign a size variable (as size for an array) that has nothing assign to it yet which will create problems, Secondly you are initializing an array first and then you are taking the size variable from user which is completely opposite of the flow, for creating arrays with dynamic size see How Dynamic Array works and is implemented in C++
Updated Code:
#include <iostream>
using namespace std;
int main()
{
int size=0, sum = 0, answer = 0,pos, max;
cin >> size;
int array[size];
int array2[size];
for (int i = 0; i < size; i++)
{
cin >> array[i];
sum+=array[i];
}
for (int i = 0; i < size; i++)
{
max = 0;
pos = 0;
for (int q = 0; q < size; q++)
{
if (array[q] > max)
{
max = array[q];
pos = q;
}
}
array2[i] = max;
array[pos] = 0;
}
for (int i = 0; i < size; i++)
{
cout << array2[i] << ", ";
}
return 0;
}
Here is the Output
Edit:
As Per #PaulMcKenzie method, the other way which is considered the appropriate one, uses the std::Vector method to initialize a dynamic array in C++, people who use the first method in visual studio might face errors,
Second Method Updated Code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int size=0, sum = 0, answer = 0,pos, max;
cin >> size;
std::vector<int> array(size), array2(size);
for (int i = 0; i < size; i++)
{
cin >> array[i];
sum+=array[i];
}
for (int i = 0; i < size; i++)
{
max = 0;
pos = 0;
for (int q = 0; q < size; q++)
{
if (array[q] > max)
{
max = array[q];
pos = q;
}
}
array2[i] = max;
array[pos] = 0;
}
for (int i = 0; i < size; i++)
{
cout << array2[i] << ", ";
}
return 0;
}
Second Output

The size of an array variable must be a compile-time constant. A user-supplied value at runtime is probably unknowable at compile time.so I recommend using std::vector instead of array.
#include <iostream>
#include<vector>
#include <algorithm>
int main()
{
int size=0, input=0;
std::cout << "enter size :";
std::cin >> size;
std::vector<int> vec;
for (size_t i{ 0 }; i < size; ++i)
{
std::cout << "enter "<<i<< ".input:";
std::cin >> input;
vec.push_back(input);
}
// Sort the elements of the vector in descending order
for (const auto& i : vec)
std::sort(vec.begin(), vec.end(), std::greater <>());
//Print the elements of the vector
for (const auto& i : vec)
std::cout << i << " ,";
return 0;
}
Output:
enter size :5
enter 0.input:1
enter 1.input:2
enter 2.input:3
enter 3.input:4
enter 4.input:5
5 ,4 ,3 ,2 ,1 ,

Related

Finding max value in a array

I'm doing a program that finds the max value in a array. I done it but I found a strange bug.
#include<iostream>
using namespace std;
int main() {
int n; //input number of elements in
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i]; //input array's elements
} int max_value = arr[0];
for (int i = 1; i <= n; i++) {
if (arr[i] > max_value) {
max_value = arr[i];
}
} cout << max_value;
return 0;
}
When I put 5 as first line for the number of elements and 2, 7, 6, 8, 9 as the elements of the array. It returns 16 instead of 9. Please help
In Arrays the first index starts with 0 and ends in n - 1 assuming the array is of length n
so when looping from i = 1 to i <= n. n is now larger than n - 1.
the solution would be to start from 0 and end at i < n hence:
#include<iostream>
using namespace std;
int main() {
int n; //input number of elements in
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i]; //input array's elements
} int max_value = arr[0];
for (int i = 0; i < n; i++) {
if (arr[i] > max_value) {
max_value = arr[i];
}
}
cout << max_value;
return 0;
}
you could also use the std::max function like so:
for(int i = 0; i < n; i ++) {
max_value = max(max_value, arr[i]);
}
The other posts already pointed out problem in your code.
You should be aware of that int arr[n]; is not permitted in standard C++.
[GCC and CLANG compiler support it in C++ as an extension]
An alternative is to allocate memory dynamically:
int *arr = new int[n];
and to find maximum value you can use std::max_element:
int max_value = *(std::max_element(arr, arr + n));
Instead of dynamic array, its better to use vector STL (make yourself familiar with Containers Library). You can do:
std::vector <int> arr;
for (int i = 0; i < n; i++) {
int input;
std::cin >> input;
arr.push_back(input);
}
int max_value = *std::max_element(arr.begin(), arr.end());
std::cout << "Max element is :" << max_value << std::endl;
in your second for do this
for (int i = 1; i < n; i++) {
if (arr[i] > max_value) {
max_value = arr[i];
}
delete '=' from i <= n because i is index which start from 0
and instead of this
int arr[n];
do this
int *arr = new int[n];

Sorting a list with indexes of another

I am trying to sort a list of indexes based on a list of string, and I receive bellow error - Segmentation fault. I cannot understand why I receive this error and how to solve it?
#include <iostream>
#include <string.h>
using namespace std;
int main() {
int size = 5;
char* mass[size];
int num[size];
for(int i = 0; i < size; i++) {
mass[i] = new char[20];
num[i] = i;
cin >> mass[i];
}
for(int i = 0; i < size; i++){
for(int j = size; j > i; j--)
if(strcmp(mass[num[j-1]], mass[num[j]]) > 0){
int tmp = num[j-1];
num[j-1] = num[j];
num[j] = tmp;
}
}
for(int i = 0; i < size; i++){
cout << mass[num[i]] << ", ";
}
return 0;
}
In the inner loop you start with j = size and then num[j] is an out-of-bounds array access.
In modern C++ you would solve this like this:
#include <iostream>
#include <array>
#include <algorithm>
int main() {
const int size = 5;
std::array<std::string, size> mass;
std::array<int, size> num;
for (int i = 0; i < size; i++) {
std::cin >> mass[i];
num[i] = i;
}
std::ranges::sort(num, [mass](int a, int b) { return mass[a] <= mass[b];});
for(int i = 0; i < size; i++){
std::cout << mass[num[i]] << ", ";
}
std::cout << std::endl;
return 0;
}

I am unable to get my code to get the stride of 7 to work properly C++

The question I am trying to solve is the following:
Write a function that traverses (and prints) the element of an array with stride =7. To do this the update part in the loop will be i= (i+7) % n, where n is the array size.
Would this function visit all elements of the array? Try different array sizes to check when it is impossible to traverse all elements.
The code that I wrote below doesn't print the correct values in the arry even if the value of i is correct.
Can anyone help, I would really appreciate it.
#include <fstream>
#include <stdlib.h>
using namespace std;
int* CreateArray(int n);
void StrideArray(int arr[], int n);
int main()
{
int* arr = new int[3];
arr = CreateArray(3);
cout << "The Elements In The Array Are: " << endl;
for (int i = 0; i < 3; i++)
{
cout << arr[i] << " ";
}
cout << endl;
StrideArray(arr, 3);
cout << "The Elements In The Array Stride 7 Are: " << endl;
for (int i = 0; i < 3; i++)
{
cout << arr[i] << " ";
}
delete[] arr;
return 0;
}
int* CreateArray(int n)
{
int* arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = (rand() % 100);
}
return arr;
}
void StrideArray(int arr[], int n)
{
int i = 0;
for (int j = 0; j < n; j++)
{
i = (i + 7) % n;
arr[j] = arr[i];
}
}
The problem is in StrideArray you read back the modified values of arr.
void StrideArray(int arr[], int n)
{
int i = 0;
int puffer=new int[n];
for (int j = 0; j < n; j++)
{
i = (i + 7) % n;
puffer[j] = arr[i];
}
for (int j = 0; j < n; j++){
puffer[j] = arr[j];
}
debete[] puffer;
}
Is a good way to write the function.
Also it visits all element only if n isn't dividable by 7. So if n is not 7,14,21,...
Also to use cout you have to #include <iostream>
Your StrideArray function needs fixing; you are iterating over j but using i to index, which remains constant; and you are reassigning value at one index to another where as you are supposed to print it:
void StrideArray(int arr[], int n)
{
int i = 0;
for (int j = 0; j < n; j=j+7)
{
cout << arr[j] << endl;
}
}
I modified the rest of your code for demo:
#include <iostream>
#include <stdlib.h>
using namespace std;
int* CreateArray(int n);
void StrideArray(int arr[], int n);
int main()
{
int* arr = new int[3];
arr = CreateArray(21);
cout << "The Elements In The Array Are: " << endl;
for (int i = 0; i < 21; i++)
{
cout << arr[i] << " ";
}
cout << endl;
StrideArray(arr, 21);
delete[] arr;
return 0;
}
int* CreateArray(int n)
{
int* arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = (rand() % 100);
}
return arr;
}

How do I put any value X after all the minimums in an array?

If I enter an array , at first the code finds the minimums then I want to put zeroes after all the minimums . For example
given an array = 1,1,3,1,1
As we see 1s are the minimum so the result should be = 1,0,1,0,3,1,0,1,0
CODE
#include <pch.h>
#include <iostream>
int main()
{
int min = 10000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] > min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the
i++; // `for loop k` to be precise)
n++;
}
std::cout << array[i] << ", 0";
}
return 0;
}
But my answer doen't put zeroes exactly after minimums
There are few issues in your code, first of all your min is wrong. I have fixed your code with comments on fixes I have made. Please take a look :
#include "stdafx.h"
#include <iostream>
int main()
{
int min = 10000;
bool found = 0;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] < min) //< instead of >
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min)
{
for (int k = n; k > i; k--)
{
array[k] = array[k - 1];
}
array[i + 1] = 0;
i++; //increment i here because you don't want to consider 0 that you have just added above.
n++; //since total number of elements in the array has increased by one (because of 0 that we added), we need to increment n
}
}
//print the array separately
for (int i = 0; i < n; i++)
{
std::cout << array[i];
if (i != n - 1)
{
std::cout << ",";
}
}
return 0;
}
The first issue was in the calculation of min: < instead of >.
Another problem if that you are modifyng the paramers iand ninside the loop. This is rather dangerous and implies to be very cautious.
Another issue was that it should be i++; n++; instead of i--,n--;
Here is the code:
// #include <pch.h>
#include <iostream>
int main()
{
int min = 1000000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] < min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the)
i++;
n++;
}
}
for (int i = 0; i < n; i++) {
std::cout << array[i] << " ";
}
std::cout << "\n";
return 0;
}

Heap corruption detected error in C++

Here is my code:
#include<iostream>
#include<cstdlib>
using namespace std;
int main() {
int** arr=NULL;
int num=0;
cin >> num;
int* big=NULL;
arr = new int*[num];
for (int i = 0; i < num; i++) {
arr[i] = new int[5];
}
big = new int[num];
for (int i = 0; i < num; i++) {
for (int j = 0; j < 5; j++) {
while (1) {
cin >> arr[i][j];
if (arr[i][j] >= 0 && arr[i][j] < 100)
break;
}
}
}
for (int i = 0; i < 5; i++) {
big[i] = 0;
}
for (int i = 0; i < num; i++) {
for (int j = 0; j < 5; j++) {
if (big[i] < arr[i][j]) {
big[i] = arr[i][j];
}
}
}
for (int i = 0; i < num; i++) {
cout << "Case #" << i + 1 << ": " << big[i] << endl;
}
delete[]big;
for (int i = num-1; i>=0; i--) {
delete[]arr[i];
}
delete[]arr;
return 0;
}
When I run this code, it says that there are heap corruption error (heap corruption detected). I think it means that there are some errors at 'new' or 'delete' parts in my codes, but I cannot find them. I hope someone to answer. Thanks.
Error is here:
big = new int[num];
...
for (int i = 0; i < 5; i++) {
big[i] = 0;
}
So when you have num less than 5 you are writing outside the array.
Anyway you are using C++ so use vector for such tasks.
#include<iostream>
#include<cstdlib>
#include<vector>
using namespace std;
int main() {
vector<vector<int>> arr;
int num=0;
cin >> num;
arr.resize(num, vector<int>(5));
for (auto &row : arr) {
for (auto &cell : row) {
while (1) {
cin >> cell ;
if (cell >= 0 && cell < 100)
break;
}
}
}
vector<int> big(arr.size());
for (int i = 0; i < arr.size(); i++) {
for (auto &cell : arr[i]) {
if (big[i] < cell) {
big[i] = cell;
}
}
}
for (int i = 0; i < num; i++) {
cout << "Case #" << i + 1 << ": " << big[i] << endl;
}
return 0;
}
In many places in your code, you're indexing your big array using indexes from 0 to 5, while the array is allocated using user input, if user input was 4 for example, your code is undefined behavior.
If you're using c++, you shouldn't be manually allocating the arrays, use std::vector instead, it will take care of managing memory for you, so you don't have to new and delete memory yourself.
With std::vector, your code would look somewhat like this.
std::vector<std::vector<int>> arr;
std::vector<int> big;
cin>>num;
arr.resize(num, std::vector<int>(5));
big.resize(5);
You will also be able to use at method to access elements while bound-checking, and size method to get the number of elements of the array.