Beginner
Beginner

Reputation: 749

logical error in sorting of array

Problem-
To sort array in such a way that number greater than first element is on right side and less than first element is on left side
Sample input-
5
4 5 3 7 2 (Taking 4 as reference)
Sample output
3 2 4 5 7
My code is sorting in this way
Input
5
12
16
2
3
56
output
2
3
2
3
56

int main()
{

   int i,j,n,temp;
   printf("enter no of elements of array");
   scanf("%d",&n);
   int a[n];
   printf("enter array\n");
     for(i=0;i<=n-1;i++)
     {
     scanf("%d",&a[i]);
     }
   j=0;
   for(i=1;i<=n-1;i++)
   {
   if(a[i]<a[j])
     {
     temp=a[j];
     a[j]=a[i];
     a[i]=a[j];
     j++;
     }
   }
  for(i=0;i<n;i++)
  {
  printf("Array is%d\n",a[i]);
  }
}

Upvotes: 0

Views: 147

Answers (4)

Anbu.Sankar
Anbu.Sankar

Reputation: 1346

for(i=1;i<=n-1;i++)
{
 if(a[i]<a[j])
 {
 temp=a[j];
 a[j]=a[i];
 a[i]=a[j];// change to a[i]=temp;
 j++;
 }
}

In this loop only you tried to sort your array elements. You have to modify your sorting mechanism with correcting your swap function last statement.

Upvotes: 1

Santosh A
Santosh A

Reputation: 5341

Also, in your program you have a variable length array which isn't valid in standard C.

printf("enter no of elements of array");
scanf("%d",&n);
int a[n];

It may work, but if you try to initialize to any value or zero then you may face the following error.

[Error] variable-sized object may not be initialized  

Here for a[n] the memory will be allocated on the stack which is not very good for large. You can only define the length of an array with a constant. (such as) int a[10];

Upvotes: 1

BLUEPIXY
BLUEPIXY

Reputation: 40145

j=0;
for(i=1;i<=n-1;i++){
    if(a[i]<a[0]){
        temp=a[j+1];
        a[j+1]=a[i];
        a[i]=temp;
        j++;
    }
}
temp = a[0];
a[0] = a[j];
a[j] = temp;

Upvotes: 0

noelicus
noelicus

Reputation: 15055

Firstly,

 temp=a[j];
 a[j]=a[i];
 a[i]=a[j];

should be

 temp=a[j];
 a[j]=a[i];
 a[i]=temp;

That explains the duplicates. But once you've sorted (ha ha) that out you'll find that it's not quite right as you only compare each number to its neighbour - what if the last number in the array is the smallest? - you'll only move it to one position earlier (e.g. 4th position in a list of 5 numbers).

Upvotes: 2

Related Questions