0

I want to sort an array of int from the smallest value to the greatest one. I have created the next algorithm but the problem is that the new array does't receive the right values from the if statement. I am going put my code bellow.

 public static void main(String[] args) {
    int[] arr = {33,44,22,11,22,11};
    int[] arrSort = new int[6];
    int temp=0;
        for (int i = 0; i < arrSort.length - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                temp = arr[i + 1];
                arr[i + 1] = arr[i];
                arrSort[i] = temp;
            }

            else {
                arrSort[i] = arr[i];
            }
        }
    System.out.println(Arrays.toString(arrSort));
}

If i run the code I get the next values: [33, 22, 11, 22, 11, 0];

I just want to figure out what part of the algorithm was thought wrong. Thank you in advance.

John R.
  • 420
  • 4
  • 14

6 Answers6

1
You need to apply 2 loops.
1st loop is to access 1st arr element.
2nd loop is to access next(1st + 1)th element.
After comparing 1st element with other swap it accordingly. 

public static void main(String []args)
     {
        int[] arr = {33,44,22,11,22,11};
        int len=arr.length;
        int temp=0,i,j;

        for (i = 0; i < len; i++) 
        {
            for (j = i+1; j < len; j++)
            {
                if (arr[i] > arr[j]) 
                {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        for(i=0; i<arr.length; i++)
        {
            System.out.println(arr[i]);
        }
     }
1

when it is the case of array Loops are very handy to use.

int[] yourArary = new int[10];
    ArrayList<Integer> intArray = new ArrayList<>();
            for( int value : yourArary ){
               intArray.add( value );
               }   
            
       Arrays.sort(intArray);
            
      System.out.println(Arrays.toString(yourArary));


//  you can short like this in reverse order
for (int i = yourArary.length - 1; i >= 0; i--)
    System.out.print(yourArary[i] + " ");
System.out.println();
TanvirChowdhury
  • 2,498
  • 23
  • 28
0

You cannot do it with just one loop. Sorting is a more complex than that. For bubble sort or selection sort it's like O(n^2). There are better algorithms that like quick sort or merge sort that have better results and aim for O(n log N) complexity. But anyway you can do it like that for example for a simple bubble sort implementation:

 int[] arr = {33,44,22,11,22,11};
  for (int i = 0; i < arrSort.length - 1; i++) {
                    for(int j=i;j<arrSort.length; j++) {
                         if (arr[i] > arr[j]) {
                                temp = arr[j];
                                arr[j] = arr[i];
                                arr[i]=temp;
                            }
                    }   
  System.out.println(Arrays.toString(arr));
Veselin Davidov
  • 7,031
  • 1
  • 15
  • 23
0

Don't know if this will help you, but why sort it by yourself, if Java can do the Job:

int[] unsortedArray = { 33, 44, 22, 11, 22, 11 };
ArrayList<Integer> intArray = new ArrayList<>();
for( int value : unsortedArray )
{
  intArray.add( value );
}

Collections.sort( intArray );
System.out.println( intArray );
baalus
  • 11
  • 3
0

If you use the helper variable temp to move positions, you don't need a second array, just put it back into arr[i]. Second, one run is not enough, you will need to run this, until there are no position changes needed. So it would look like this:

public static void main(String[] args) {
    //source Array
    int[] arr = {33,44,22,11,22,11};
    int temp=0;
    //marker, that positions were switched
    boolean sthChanged = false;
    do
    {
        //in each run assume that nothing is left to change
        sthChanged = false;

        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                //we found an instance, where the earlier position holds a higher int than the latter

                //save the latter value in the temp variable
                temp = arr[i + 1];
                //move the former value to the latter position
                arr[i + 1] = arr[i];
                //fill the former position with the value from the temp variable
                arr[i] = temp;
                //set the marker to true, as there might be other changes to be done
                sthChanged = true;
            }
        }
    }
    while (sthChanged); //stop only, if we didn't find sth to be changed in the last run

    System.out.println(Arrays.toString(arr));
}

Best regards

DeeP
  • 43
  • 1
  • 3
  • Thank you very much for your answer. Can you explain me a bit more how does the boolean value "sthChanged" know when there is nothing else to be change? – John R. May 25 '18 at 10:03
  • Hi, in every loop we set it first to false before going through the whole array. It will be set to true only, if we found a case in the array, where the former value was bigger than the one following it. SO when we reach the while statement, the variable will still be false if nothing was changed in this run. And if we didn't switch any positions then it doesn't make sense to do another round. – DeeP May 25 '18 at 11:51
0

First of all, u shud not use two arrays in your algorithm, as its just a waste of memory and unecessary array access overhead. If u need to retain the original array copy it over, and send the copied array to the sort method.

Secondly, for the method adopted here (bubble sort), you are iterating the array and finding the largest element and shifting it to the end. U need to repeat this process, for each subarray of length-1, length-2 ... 1. So the time complexity of this approach would be O(n^2). There are better algorithms, like MergeSort, QuickSort which can do the sort in the theoretical O(n log(n)) time.

See below the correctin required for your code :

public static void main(String[] args) {
        int[] arr = {33,44,22,11,22,11};
        //int[] arrSort = new int[6];
        int temp=0;
        for(int j = 0; j < arr.length; j++) {
            for (int i = 0; i < arr.length - 1; i++) {
                if (arr[i] > arr[i + 1]) {
                    temp = arr[i + 1];
                    arr[i + 1] = arr[i];
                    arr[i] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(arr));
    } 
JineshEP
  • 738
  • 4
  • 7