John R.
John R.

Reputation: 420

Algorithm for sorting an array in java

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.

Upvotes: 0

Views: 238

Answers (6)

TanvirChowdhury
TanvirChowdhury

Reputation: 2445

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();

Upvotes: 1

JineshEP
JineshEP

Reputation: 748

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));
    } 

Upvotes: 0

user9243381
user9243381

Reputation: 11

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]);
        }
     }

Upvotes: 1

DeeP
DeeP

Reputation: 43

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

Upvotes: 0

baalus
baalus

Reputation: 11

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 );

Upvotes: 0

Veselin Davidov
Veselin Davidov

Reputation: 7081

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));

Upvotes: 0

Related Questions