# SORTING ALGORITHMS...

• October 14th, 2011, 11:33 AM
Medo Almasry
SORTING ALGORITHMS...
Code :

```public class PAS2 {   public static void main(String[] args) { int[] x = {1,4,2,6,5,3,4}; for(int z : modifiedselectionsort(x)){ System.out.print(z + "\t"); }   public static int[] modifiedselectionsort(int[] x){ for(int i = 0; i < x.length/2; i++){ int min = x[i]; int max = x[i]; int minindex = i; int maxindex = i; for(int j = i+1; j < x.length-i; j++){ if(x[j] < min){ min = x[j]; minindex = j; } if(x[j] >= max){ max = x[j]; maxindex = j; } } [SIZE=4][FONT=Comic Sans MS]if (maxindex == i){ maxindex = minindex; // Algorithm's approach to max at beginning }[/FONT][/SIZE] int temp1 = x[i]; int temp2 = x[x.length-1-i]; x[i] = min; x[x.length-1-i] = max; x[minindex] = temp1; x[maxindex] = temp2; } return x; } }```
Now the whole problem is with that IF STATEMENT...
if u don't use it and put {6,4,5} u will get 566 which is wrong but when u add that if statement (modification to adapt maximum numbers at 1st) and presumably everything is fine now but when I use an array like the one am using in this code u get 123381...
ANYBODY EXPLAIN WHY? ;/
• October 14th, 2011, 04:31 PM
kenster421
Re: SORTING ALGORITHMS...
First, read this on Selection Sort: Selection sort - Wikipedia, the free encyclopedia.

Make sure you are following that algorithm.

If the length of the arrary is n, you will make n passes. On your (i)th pass, you need to find the (i)th smallest number and insert it at index i.

In a selection sort, the max doesn't matter, only the min matters.
• October 14th, 2011, 04:32 PM
helloworld922
Re: SORTING ALGORITHMS...
or only the max matters and the min doesn't matter (depending on how you want to sort).
• October 14th, 2011, 09:18 PM
Medo Almasry
Re: SORTING ALGORITHMS...
Actually I appreciate your help both of you...
but this is a MODIFIED SELECTION SORT :D
The purpose is to find min and post it at beginning, find max and post it at the end in every pass...