I'm very new to C or even coding. I was trying to make a simple array sorter, where the I first input the number of elements that will be in the array and then input the elements. My outcome should be the array sorted in ascending order. I have not thought about the case if elements inserted are same. So I would love to get some help from you folks. The main error that I'm facing is that only the first unsorted element is sorted while the rest are either interchanged or left the same.
int main(){
int x;
cout<<"Enter no. of elements"<<endl;
cin>>x;
int A[x];
for (int i = 0;i<x;i ){
cin>>A[i];
}
for(int i=0;i<x;i )
cout<<A[i]<<",";
int count=0;
if(count <= (x-1)){
for (int i=0;i<(x-1);i ){
if(A[i]>A[i 1]){
int a;
a = A[i];
A[i] = A[(i 1)];
A[i 1] = a;
}
else if(A[i]<A[i 1])
count ;
}
}
cout<<"Sorted array:";
for(int i=0;i<x;i )
cout<<A[i]<<",";
return 0;
}
CodePudding user response:
You declared a variable length array
int A[x];
because its size is not a compile-time constant.
However variable length arrays are not a standard C feature though some compilers have their own language extensions that support variable length arrays,
It is better to use the class template std::vector
.
Another problem is that it seems you are trying to use the bubble sort method to sort the array. But this method requires two loops.
Here is a demonstration program that shows how the bubble sort algorithm can be implemented.
#include <iostream>
int main()
{
int a[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
const size_t N = sizeof( a ) / sizeof( *a );
for (const auto &item : a)
{
std::cout << item << ' ';
}
std::cout << '\n';
for (size_t last = N, sorted = N; not ( last < 2 ); last = sorted)
{
for (size_t i = sorted = 1; i < last; i )
{
if (a[i] < a[i - 1])
{
// std::swap( a[i-1], a[i] );
int tmp = a[i - 1];
a[i - 1] = a[i];
a[i] = tmp;
sorted = i;
}
}
}
for (const auto &item : a)
{
std::cout << item << ' ';
}
std::cout << '\n';
}
The program output is
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
CodePudding user response:
If you are taking the size of array as input from user you have to create your array dynamically in c like int *array=new int(x) and after taking the inputs of the elements just run a nested loop from 0 to size and the inner loop from 0 to size-1 and check if(A[i]>A[i 1]) if true then swap the values else continue