0

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]);
  }
}
6
  • 3
    what is the problem? Commented Nov 6, 2014 at 10:44
  • 3
    You forgot to ask the question.. Commented Nov 6, 2014 at 10:44
  • 3
    Welcome to StackOverflow. You might want to read this: How to ask a good question. Commented Nov 6, 2014 at 10:45
  • 1
    Did you want your output like your sample output? Commented Nov 6, 2014 at 10:46
  • 1
    Edit your question and write that. Also, what does "with taking reference to first element of the array" mean? Are you supposed to traverse the array using a pointer? Commented Nov 6, 2014 at 10:46

4 Answers 4

2

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).

Sign up to request clarification or add additional context in comments.

Comments

1

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];

Comments

1
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.

Comments

0
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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.