Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
After passing 'EXAMPLE' as input the output shown is 'AELMPXE', i am not getting why one of the 'E' is not being sorted, after tracing the program i got that its not comparing after 2nd iteration with the last element, please help.

What I have tried:

C++
<pre>#include <stdio.h>
#include <stdlib.h>
#include<string.h>

void selection_sort(char a[] , int n)
{
    int pos,i,j;
    char temp;
    for(i = 0;i < n-2;i++)
    {
        pos = i;
        for(j = i + 1;j < n-1;j++)
        {
            if(a[pos] > a[j])
            {
                pos = j;
            }
        }
        temp = a[pos];
        a[pos] = a[i];
        a[i] = temp;
    }
    printf("%s",a);
}
int main()
{
    char a[30];
    int n;
    printf("Enter the string :");
    scanf("%s",a);
    n = strlen(a);
    selection_sort(a , n);
    return 0;
}
Posted
Updated 9-Sep-17 23:38pm

You need to be very careful in writing the for statement. If you use the < comparison operator, then
C++
for (i=0; i<n; ++i) {

executes for each element of an array of length n, up to the last position n-1. It does not execute for i == n

It does the same thing as a for statement with the <= comparison operator
C++
for (i=0; i<=n-1; ++i) {
 
Share this answer
 
Comments
CPallini 10-Sep-17 3:52am    
5.
Quote:
After passing 'EXAMPLE' as input the output shown is 'AELMPXE'

The last letter of user input is not sorted. This can mean only 1 thing: your sort routine stops too early and you need to add 1 to the end value in sorting routine.
You should learn to use the debugger, it allow you to see your code execute step by step.

There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900