-1

for the given code

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

void selectionSort(int arr[], int n)
{
int i, j, min_idx;

for (i = 0; i < n-1; i++)
{
    min_idx = i;
    for (j = i+1; j < n; j++)
      if (abs(arr[j]) < abs(arr[min_idx]))
        min_idx = j;
    if (abs(arr[j]) == abs(arr[min_idx])){
        if (arr[j] < arr[min_idx])
      min_idx = j;
    }
    swap(&arr[min_idx], &arr[i]);
}
}
int main()
{
int N;
scanf("%d", &N);
int i,t;
int T[N];
for(i=0;i<N;i++){
    scanf("%d",&T[i]);
}
selectionSort(T, N);
for(i=0;i<N;i++)
{printf("%d\n",T[i]);}
if(T==NULL)
{
printf("0\n");
}
 return 0;}

positive values are printed before negative values what should I do to get an output {1,2,-2,3-5,6,-7,11,-21,33} for input 10 {-21,2,11,3,-7,-2,33,-2,6,1} code URL https://ide.geeksforgeeks.org/dbGpvPBuV1

  • Is there a typo in the input you show? It does not contain a `-5`, but there is a `-5` in the desired output you show. – Eric Postpischil Jun 06 '21 at 10:55
  • 2
    When discussing the input and output of a program, show it **exactly** as it is in the computer. Do not add extra braces or commas. Presumably your actual input is something like `10 -21 2 11 3 -7 -2 33 -5 6 1`, not `10 {-21,2,11,3,-7,-2,33,-2,6,1}`. Adding these extra characters can confuse readers. – Eric Postpischil Jun 06 '21 at 10:56

1 Answers1

0

Your loop on j fails to use braces to enclose all the statements you want in the loop. Your code is:

    for (j = i+1; j < n; j++)
        if (abs(arr[j]) < abs(arr[min_idx]))
            min_idx = j;
    if (abs(arr[j]) == abs(arr[min_idx])){
        if (arr[j] < arr[min_idx])
            min_idx = j;
    }
}

but it should be:

    for (j = i+1; j < n; j++) {
        if (abs(arr[j]) < abs(arr[min_idx]))
            min_idx = j;
        if (abs(arr[j]) == abs(arr[min_idx])){
            if (arr[j] < arr[min_idx])
                min_idx = j;
        }
    }

Also, since you want positive numbers first, arr[j] < arr[min_idx] should be arr[j] > arr[min_idx].

Generally, do not declare loop indices outside a loop. Delete the line int i, j, min_idx;. Change for (i = 0; i < n-1; i++) to for (int i = 0; i < n-1; i++), change for (j = i+1; j < n; j++) to for (int j = i+1; j < n; j++), and change min_idx = i; to int min_idx = i;. If you had written the code this way in the first place, the compiler would have warned you about the lines erroneously outside the loop because the declaration of j would not be in scope for those lines. You would have found the error sooner.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312