C++ sorting an array in ascending order Printing - c++

Im trying to sort an array in ascending order and print it out and Im having trouble of where to put my cout in my code.
for (int k=0; k<ARRAY_SIZE; k++) {
for (int l=1; l<ARRAY_SIZE-1; l++) {
if(numbers[l] > numbers[k]) {
temp = numbers[k];
numbers[k] = numbers[l];
numbers[l] = temp;
}
cout<<numbers[k];
}
}

If you want to see the result of sorting you have to print the array in new for loop

Remove the actual cout and put it after the sorting loop, in a new loop
for(int k = 0 ; k < ARRAY_SIZE; ++k)
cout << numbers[k] << " ";

This is a program that finds the length of a number n and converts it to an array arr and sorts that array in ascending order.(possible aptitude question)
#include <iostream>
using namespace std;
int main()
{
int n,i=0,j,num,temp,len=0,arr[10]={0};
cin>>n;
num=n;
while(n!=0)
{
len++;
n/=10;
}
cout<<len<<endl;
for ( i = len; i >= 0; i--)
{
arr[i] = num%10;
num/=10;
}
for(i=1;i<=len;i++)
for(j=0;j<=len-i;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
for(i=1;i<=len;i++)
{
cout<<arr[i]<<endl;
}
return 0;
}

try this :
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
//array declaration
int arr[] = {1,2,5,8,4,3};
int n,i,j;
n = sizeof(arr) / sizeof(arr[0]);
int temp;
//print input elements
cout<<"Unsorted Array elements:"<<endl;
for(i=0;i<n;i++)
if(arr[i] == arr[n - 1]){
cout<<arr[i]<<"";
}else{
cout<<arr[i]<<",";
}
cout<<endl;
//sorting - ASCENDING ORDER
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
temp =arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
//print sorted array elements
cout<<"Sorted (Ascending Order) Array elements:"<<endl;
for(i=0;i<n;i++)
if(arr[i] == arr[n - 1]){
cout<<arr[i]<<"";
}else{
cout<<arr[i]<<",";
}
cout<<endl;
return 0;
}

Related

Merge Sort: segmentation fault c++

For some odd reason, I am getting a segmentation fault when I call the merge function. I am using g++ to compile and have tried passing in different data for the parameters, but I still get this issue.
#include <iostream>
using namespace std;
// Merges two sorted subarrays of A[].
// First sorted subarray is A[l..m].
// Second sorted subarray is A[m+1..r].
// You might want to call this function in function mergeSort().
void merge(int A[], int l, int m, int r) {
int i = 1; //Starting index for left sub array
int j = m + 1; //Starting index for right sub array
int k = 1; //starting index for temp
int *temp = new int[r];
while (i <= m && j <= r) {
if (A[i] <= A[j]) {
temp[k] = A[i]; //A[i] is actually smoler than A[j]
i++;
k++;
}
else {
if (A[i] <= A[j]) {
temp[k] = A[i]; //A[j] is actually smoler than A[i]
j++;
k++;
}
}
//Copy all elements from left sbuarray to temp
while(i<=m){
temp[k] = A[i];
i++;
k++;
}
//Copy all elements from right subarray to temp
while(j<=r){
temp[k] = A[j];
i++;
k++;
}
for(int z =0; z <r; z++){
A[z] = temp[z];
}
}
}
// using mergeSort to sort sub-array A[l..r]
// l is for left index and r is right index of the
// sub-array of A[] to be sorted
void mergeSort(int A[], int l, int r) {
if (l < r) {
int middle = l + (r - l) / 2;
mergeSort(A, l, middle);
mergeSort(A, middle + 1, r);
merge(A, l, middle, r);
}
}
int main() {
cout << "Please enter the length (number of elements) of the input array: ";
int n;
cin >> n;
if (n <= 0) {
cout << "Illegal input array length!" << endl;
return 0;
}
int *A = new int[n];
cout << "Please enter each element in the array" << endl;
cout << "(each element must be an integer within the range of int type)."
<< endl;
for (int i = 0; i < n; i++) {
cout << "A[" << i << "] = ";
cin >> A[i];
}
cout << "Given array A[] is: ";
for (int i = 0; i < n - 1; i++)
cout << A[i] << ",";
cout << A[n - 1] << endl;
mergeSort(A, 0, n - 1);
cout << "After mergeSort, sorted array A[] is: ";
for (int i = 0; i < n - 1; i++)
cout << A[i] << ",";
cout << A[n - 1] << endl;
delete[] A;
return 0;
}
The merge function is the problem of my program. I have tried debugging and whatnot but cannot determine the problem.
Try using the below code :-
#include<iostream>
using namespace std;
void merge(int arr[],int l,int m,int h)
{
int n1=m-l+1;
int n2=h-m;
int L[n1],M[n2];
for(int i=0;i<n1;i++)
L[i]=arr[l+i];
for(int i=0;i<n2;i++)
M[i]=arr[m+1+i];
int i=0,j=0,k=l;
while(i<n1&&j<n2)
{
if(L[i]<=M[j])
arr[k++]=L[i++];
else
arr[k++]=M[j++];
}
while(i<n1)
arr[k++]=L[i++];
while(j<n2)
arr[k++]=M[j++];
}
void mergesort(int arr[],int l,int h)
{
if(l>=h)
return;
int m=l+(h-l)/2;
mergesort(arr,l,m);
mergesort(arr,m+1,h);
merge(arr,l,m,h);
}
int main()
{
int n;
cout<<"Enter the no of element to be sorted:- ";
cin>>n;
int arr[1000000];
for(int i=0;i<n;i++)
arr[i]=rand();
mergesort(arr,0,n-1);
for(int i=0;i<n;i++)
cout<<arr[i]<<endl;
}
here is the output on online compiler:-
The problem is in this block of code.
while (j <= r) {
temp[k] = A[j];
i++; // Here it should be j++ instead of i++
k++;
}
You are incrementing i whereas you should increment j. This still produces the wrong output though.
Use debugger to find what's wrong with your code.

Bubble sort with array size

I want to do bubble sort for n elements of arraylist. Instead of declaring the arraylist first like below, I want to create the arraylist using for loops.
So this is the code of declaring the arraylist first:
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
int comparisons=0;
for (i = 0; i < n-1; i++) {
swapped = false;
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
{
comparisons++;
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
swapped = true;
}
}
if (swapped == false)
break;
}
cout << "Number of comparisons = " << comparisons << endl;
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = 5;
bubbleSort(arr, n);
cout<<"Sorted array: \n";
printArray(arr, n);
}
which I do not want to do.
I have made this, but I do not know why it does not work. I'm still quite new with C++. May I know what's the problem. Thank you so much.
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
int comparisons=0;
for (i = 0; i < n-1; i++) {
swapped = false;
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
{
comparisons++;
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
swapped = true;
}
}
if (swapped == false)
break;
}
cout << "Number of comparisons = " << comparisons << endl;
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
There are two problems:
Arrays are 0-indexed.
Variable length array which is not really legal in C++.
So write main like:
// Driver code
int main()
{
int n = 5;
int* arr = new int[n];
for(int i=0; i<n; i++){
arr[i]=i+1;
cout<<arr[i];
cout<<endl;
}
bubbleSort(arr, n);
cout<<"Sorted array: \n";
printArray(arr, n);
delete[] arr;
}

Selection Sort in c++

i'm trying to understand selection sort from this video:
https://www.youtube.com/watch?v=79AB11J5BqU
this is my current code :
#include <iostream>
int main() {
int numbers[5]={5,3,4,1,2};
int temp;
std::cout<<"BEFORE SORT : \n";
for(int x=0;x<5;x++){
std::cout<<numbers[x]<<" ";
}
for (int i = 0; i < 5; ++i) {
for (int j = i+1; j < 5; ++j) {
if(numbers[j]<numbers[i]){
temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
}
}
std::cout<<"\n\nAFTER SORT : \n";
for(int x=0;x<5;x++){
std::cout<<numbers[x]<<" ";
}
}
Am i doing the selection sort just like the video?
or am i instead doing buble sort ?
Thanks
In selection sort you find a minimal (or maximal) element and put it to top (bottom), then repeat it again for the rest of list.
It would be a selection sort, but you don't need to do swap every number you compare to find the smallest one. Store smallest number index in each internal loop and do one swap at the end of it.
unsigned minIndex;
for (int i = 0; i < 5; ++i) {
minIndex = i;
for (int j = i + 1; j < 5; ++j) {
if(numbers[j] < numbers[minIndex]){
minIndex = j;
}
}
if (minIndex != i) { // Do swapping
temp = numbers[i];
numbers[i] = numbers[minIndex];
numbers[minIndex] = temp;
}
}
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning.
#include<iostream>
using namespace std;
// Selection Sort//
void Selection_Sort(int a[],int n)
{
for(int i=0;i<n-1;i++)
{
int min_index=i;
for(int j=i;j<n-1;j++)
{
if(a[j]<a[min_index]){
min_index=j;
}
}
swap(a[i],a[min_index]);
}
}
int main()
{
int n,key;
cin>>n;
int a[1000];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
Selection_Sort(a,n);
for(int i=0;i<n;i++)
{
cout<<a[i];
}
}

How do I change postition of number in 2d array in c++?

I tried to find the biggest number in every row of a 2D array, and to put it on diametrum. I did that, but I now want to replace that number, not just declare them on diametrum. How do I change the place of numbers for my case? Here's code:
#include<iostream>
using namespace std;
int mac(int b[],int n)
{
int i,max,c=0;
max=b[0];
for(i=0;i<n;i++)
{
if(max<b[i]) {max=b[i];c=i;}
}
return c;
}
int main()
{
int i,j,n;
int c;
int a[10][10],b[10];
cin>>n;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cin>>a[i][j];
cin.ignore();
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
b[j]=a[i][j];
c=mac(b,n);
/*Place where i should change something*/
a[i][i]=a[i][c];
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout<<a[i][j];
}
cout<<endl;
}
return 0;
}
You need to do swap. So you have to define one temporary variable to save actual value from [i][i]. Then overwrite position [i][i] with max value and at the end you need place temp value back to position where you found max value.
/*Place where i should change something*/
int temp = a[i][i];
a[i][i] = a[i][c];
a[i][c] = temp;
Assuming that when n = 3, and input is 1 2 3 4 5 6 7 8 9 the output should be 321 465 789
The code should be
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector< vector<int> > a;
size_t n;
cout<<"Enter number of value for N: ";
cin>>n;
a.reserve(n);
for (size_t i = 0; i<n;i++) {
a[i].reserve(n);
for (size_t j =0 ; j<n;j++) {
cin>>a[i][j];
}
}
for (size_t i = 0; i<n;i++) {
size_t index = 0;
int max = INT_MIN;
for (size_t j =0 ; j<n;j++) {
if (a[i][j] >= max) {
max = a[i][j];
index = j;
}
}
a[i][index] = a[i][i];
a[i][i] = max;
}
cout<<"\nOutput\n";
for (size_t i = 0; i<n;i++) {
for (size_t j =0 ; j<n;j++) {
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}

Using a function to remove duplicates from an array in C++

I'm writing a program that has a user input integers into an array, calls a function that removes duplicates from that array, and then prints out the modified array. When I run it, it lets me input values into the array, but then gives me a "Segmentation fault" error message when I'm done inputing values. What am I doing wrong?
Here is my code:
#include <iostream>
using namespace std;
void rmDup(int array[], int& size)
{
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[i] == array[j])
{
array[i - 1 ] = array[i];
size--;
}
}
}
}
int main()
{
const int CAPACITY = 100;
int values[CAPACITY], currentSize = 0, input;
cout << "Please enter a series of up to 100 integers. Press 'q' to quit. ";
while (cin >> input)
{
if (currentSize < CAPACITY)
{
values[currentSize] = input;
currentSize++;
}
}
rmDup(values, currentSize);
for (int k = 0; k < currentSize; k++)
{
cout << values[k];
}
return 0;
}
Thank you.
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[i] == array[j])
{
array[i - 1 ] = array[i]; /* WRONG! array[-1] = something */
size--;
}
}
}
If array[0] and array[1] are equal, array[0-1] = array[0], meaning that array[-1] = array[0]. You are not supposed to access array[-1].
I wouldn't make it even possible to create duplicates:
int main()
{
const int CAPACITY = 100;
cout << "Please enter a series of up to 100 integers. Press 'q' to quit. ";
std::set<int> myInts;
int input;
while (std::cin >> input && input != 'q' && myInts.size() <= CAPACITY) //note: 113 stops the loop, too!
myInts.insert(input);
std::cout << "Count: " << myInts.size();
}
And do yourself a favour and don't use raw arrays. Check out the STL.
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
vector<int> vec = {1,1,2,3,3,4,4,5,6,6};
auto it = vec.begin();
while(it != vec.end())
{
it = adjacent_find(vec.begin(),vec.end());
if(it != vec.end())
vec.erase(it);
continue;
}
for_each(vec.begin(),vec.end(),[](const int elem){cout << elem;});
return 0;
}
This code compiles with C++11.
#include<iostream>
#include<stdio.h>
using namespace std;
int arr[10];
int n;
void RemoveDuplicates(int arr[]);
void Print(int arr[]);
int main()
{
cout<<"enter size of an array"<<endl;
cin>>n;
cout<<"enter array elements:-"<<endl;
for(int i=0;i<n ;i++)
{
cin>>arr[i];
}
RemoveDuplicates(arr);
Print(arr);
}
void RemoveDuplicates(int arr[])
{
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;)
{
if(arr[i]==arr[j])
{
for(int k=j;k<n;k++)
{
arr[k]=arr[k+1];
}
n--;
}
else
j++;
}
}
}
void Print(int arr[])
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
}