Sorting a randomized array in Java -


i trying make app sorting randomized array made code , can not see wrong it returns wrong values notes: trying learn programming. don't suggest whole different ways of solving problem. want see wrong code can better. randomarraycreator.create() returns array of numbers in randomized order.

public class arraysorter { public static void main(string[] args) {     int[] siyahi = randomarraycreator.create();     int[] siralanmish = new int[siyahi.length];      (int i=0;i<siyahi.length;i++)     {         (int j=0;j<siyahi.length;j++)         {             (int k=j+1;k<siyahi.length;k++)             {                 if (siyahi[k]<siyahi[j]) j=k;             }             siralanmish[i]=siyahi[j];             siyahi[j]=siyahi.length+1;         }         system.out.println(siralanmish[i]);     } } 

}

given mentioned wanted learn how improve current program, here minimalist changes have code produce sorted array.

a few notes on changes:

1.

if (siyahi[k]<siyahi[j]) j=k; 

this assume trying swap values @ each indexes. instead assigning value of k j cause problems entire loop. replaced following:

    if (siyahi[k]<siyahi[j])      {         int temp = siyahi[j];         siyahi[j] = siyahi[k];         siyahi[k] = temp;     }  

this creates temporary variable store 1 of values can swap value @ each index without losing 1 of values.

2.

siralanmish[i]=siyahi[j]; 

this replaced with:

siralanmish[j]=siyahi[j]; 

this allows directly copy values same index source array target array.

3.

siyahi[j]=siyahi.length+1; 

this code fill array value of length+1 original array , lose other values.

your code fixes below:

    public class arraysorter     {     public static void main(string[] args)     {         int[] siyahi = randomarraycreator.create();         int[] siralanmish = new int[siyahi.length];          (int i=0;i<siyahi.length;i++)         {             (int j=0;j<siyahi.length;j++)             {                 (int k=j+1;k<siyahi.length;k++)                 {                     if (siyahi[k]<siyahi[j])                      {                       int temp = siyahi[j];                       siyahi[j] = siyahi[k];                       siyahi[k] = temp;                     }                 }                 siralanmish[j]=siyahi[j];             }             system.out.println(siralanmish[i]);         }     } 

Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -