I am trying to make a simple program in C to implement Selection Sort.
Below is my program:
#include<stdio.h>
#include<conio.h>
int main(void)
{
int min, total, *arr,i,j,temp;
clrscr();
printf("Enter the size of array : ");
scanf("%d",&total);
arr = (int *) malloc(total * sizeof(int));
for(i = 0; i<total; i++)
{
printf("\nEnter element %d: ", i+1);
scanf("%d", &arr[i]);
}
min = arr[0];
for(i = 0; i<total; i++)
{
for(j = i; j<total; j++)
{
if(arr[j]<min)
{ min=arr[j]; }
}
min = temp;
min = arr[i];
arr[i] = min;
}
for(i = 0; i<total; i++)
{
printf("%d \t", arr[i]);
}
getch();
return 0;
}
Output:

The answer should have been
10 20 30 40 70 80
How can I fix my program?
EDIT 1:
Fixed Temp Issue after reading cnicutar’s answer
min = arr[0];
for(i = 0; i<total; i++)
{
for(j = i; j<total; j++)
{
if(arr[j]<min)
{
min=arr[j];
min_index = j;
}
}
temp = a[i];
a[i] = min;
a[min_index] = temp;
}
Now, I get this for the above input values: 10 10 10 20 10 10
EDIT 2:
Found the problem, the program was using the same minimum value for all Iterations
#include<stdio.h>
#include<conio.h>
int main(void)
{
int min, min_index, total, *arr,i,j,temp;
clrscr();
printf("Enter the size of array : ");
scanf("%d",&total);
arr = (int *) malloc(total * sizeof(int));
for(i = 0; i<total; i++)
{
printf("\nEnter element %d: ", i+1);
scanf("%d", &arr[i]);
}
min = arr[0]; // min = arr[0] = 70 || min = 10 <-- Problem
for(i = 0; i<total-1; i++) // i = 0 ||
{ // ||
for(j = i; j<total; j++) // j = i = 0 ||
{ // ||
if(arr[j]<min) // 30<70 ; 40<30 ; 10<30 ||
{ // ||
min=arr[j]; // min = 30 ; ; min = 10 ||
min_index = j; // index = 1 ; ; index = 3 ||
} // ||
} // ||
// ||
if(min!=arr[i]) // ||
{ // ||
temp = arr[i]; // ||
arr[i] = min; // ||
arr[min_index] = temp; // After swap: 10 30 40 70 80 20 ||
}
min = arr[i+1]; // (Add this to fix the problem)
}
for(i = 0; i<total; i++)
{
printf("%d \t", arr[i]);
}
getch();
return 0;
}
At least 2 problems: your “swap” is wrong:
And you should be remembering the index of the minimum element, changing
minwon’t do. Specifically: you want to changearr[mystery]wheremystery = jin yourif.