Working on a problem which uses a main only to implement Selection Sort. You enter arbitrary amount of integers and when the program runs it spits out the integers in increasing order. So the output would be something like this:

Enter Integers to sort: 3
> 1
> 8
> -5

answer:
> -5
> 1
> 8

Here is what i have done so far (note: Terminal is a class that lets me do input/output. It was custom made by someone) :

public class SelectionSort
{
  public static void main(String[] args)
  {
    // Prompt for the number of integers and put them in a array of that
    // size.

    Terminal t = new Terminal();
    int n = t.readInt("Integers to sort? ");
    int[] integerArray;
    integerArray = new int[n];

    for&#40;int i = 0; i < n; i++&#41; &#123;
      integerArray&#91;i&#93; = t.readInt&#40;"> "&#41;;
    &#125;

     // Find the index with the smallest integer.

     for&#40;int i = 0; i < integerArray.length; i++&#41; &#123;
       int start = i;
       for &#40;int x = i + 1; x < integerArray.length; x++&#41; &#123;
         if &#40;integerArray&#91;x&#93; < integerArray&#91;start&#93;&#41;
          start = x;
        &#125;

     // Use Selection Sort alogorithm to sort the array in increasing
     // order.

        int small = start;
        for &#40;int z = 0; z < integerArray.length; z++&#41; &#123;
          int tmp = integerArray&#91;small&#93;;
          integerArray&#91;small&#93; = integerArray&#91;i&#93;;
          integerArray&#91;i&#93; = tmp;

        &#125;

   &#125;
        t.println&#40;&#41;;

      // Print out the integers in increasing order.

          for&#40;int i = 0; i < n; i++&#41; &#123;
          t.println&#40;integerArray&#91;i&#93;&#41;;
         &#125;

    &#125;



&#125;

It compiles fine, but when i run it, its somewhat buggy. The problem is that when i enter a odd number at the prompt "Enter number of integers: ", it works fine. But if i enter a even number, it doesn't work so well. It just prints the integers the way they were typed instead of in increasing order like so:

Integers to sort? 2
> 2
> 1

answer:

2
1

Thanks.

I didn't very much understand your algorithm. So I will be sending the alogorithm that I have learnt. Hope its useful.

This is only the algorithm not the full program.

//Sorting in Descending Order
// arr is just an array

for(int i=0; i<arr.length-1;i++)
{
     for(int j=i+1;j<arr.length;j++)
     {
          if(arr[i] > arr[j])
          {
               int temp = arr[i];
               arr[i] = arr[j];
               arr[j] = temp;
          }
     }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.