Question:
Java sort code for an array of integers?
anonymous
1970-01-01 00:00:00 UTC
Java sort code for an array of integers?
Five answers:
anonymous
2016-04-05 11:13:02 UTC
int num=25431; int reminder; int cnt=0; int a[] = new int[5]; while(n!=0) { reminder=n%10; a[cnt++]=reminder; } Thats it , you will get yoru array a[]
anonymous
2008-04-04 12:10:32 UTC
The fastest is a Collections framework.

int[] nums = new int[] {101,22,3,94,2};

Arrays.sort(num);



that is ascending. Generics and autoboxing Java6.



============



C++ "designed to be difficult and built to stay that way."



Incidentially, the fastest bubble sort is python, hands down.
joebutnotjoe
2008-04-04 12:01:31 UTC
Wikipedia has a good page with a table listing the big O of many different sorting algorithms. I'd go with quicksort because it's fast and easily recognizable, people'd be all like "omg he can code quicksort" :)
anonymous
2008-04-04 11:51:30 UTC
Use C++, there is no such thing as fast in java.
mbspringer133b
2008-04-04 12:35:51 UTC
bubble sort ?



=======================

heres an unrelated snippet

=========================



/**

* @(#)sort.java

*

* sort application

*

* @author

* @version 1.00 2008/4/4

*/



public class sort {



public static void main(String[] args) {

String outIT ;

int iSize[] = new int [15];

int bSize[] = new int [15];



outIT = " " ;



bSize[1] = 0 ; bSize[2] = 0 ; bSize[3] = 0 ; bSize[4] = 0 ;

bSize[5] = 0 ; bSize[6] = 0 ; bSize[7] = 0 ;

bSize[8] = 0 ; bSize[9] = 0 ; bSize[10] = 0 ;



//



iSize[1] = 11 ; iSize[2] = 12;iSize[3] = 13 ;iSize[4] = 33 ;

iSize[5] = 15 ;iSize[6] = 16;iSize[7] = 4 ;

iSize[8] = 18 ;iSize[9] = 19;iSize[10] = 5;



int i;

for (i=1; i<10; i++)

if (iSize[i] > iSize[i+1])

{ bSize[i] = iSize[i] ;

outIT =outIT + String.valueOf(bSize[i] + " , ");

}

else { bSize[i] = iSize[i+1] ;

outIT =outIT + String.valueOf(bSize[i] + " , ");



}

// TODO, add your application code

System.out.println(outIT);

}

}





=================================

Java Code for a Bubble Sort



In the bubbleSort.java program, shown in Listing 3.1, a class called ArrayBub encapsulates an array a[], which holds variables of type long.



In a more serious program, the data would probably consist of objects, but we use a primitive type for simplicity. (We'll see how objects are sorted in the objectSort.java program in Listing 3.4.) Also, to reduce the size of the listing, we don't show find() and delete() methods with the ArrayBub class, although they would normally be part of a such a class.

LISTING 3.1 The bubbleSort.java Program



// bubbleSort.java

// demonstrates bubble sort

// to run this program: C>java BubbleSortApp

////////////////////////////////////////////////////////////////

class ArrayBub

{

private long[] a; // ref to array a

private int nElems; // number of data items

//--------------------------------------------------------------

public ArrayBub(int max) // constructor

{

a = new long[max]; // create the array

nElems = 0; // no items yet

}

//--------------------------------------------------------------

public void insert(long value) // put element into array

{

a[nElems] = value; // insert it

nElems++; // increment size

}

//--------------------------------------------------------------

public void display() // displays array contents

{

for(int j=0; j
System.out.print(a[j] + " "); // display it

System.out.println("");

}

//--------------------------------------------------------------

public void bubbleSort()

{

int out, in;



for(out=nElems-1; out>1; out--) // outer loop (backward)

for(in=0; in
if( a[in] > a[in+1] ) // out of order?

swap(in, in+1); // swap them

} // end bubbleSort()

//--------------------------------------------------------------

private void swap(int one, int two)

{

long temp = a[one];

a[one] = a[two];

a[two] = temp;

}

//--------------------------------------------------------------

} // end class ArrayBub

////////////////////////////////////////////////////////////////

class BubbleSortApp

{

public static void main(String[] args)

{

int maxSize = 100; // array size

ArrayBub arr; // reference to array

arr = new ArrayBub(maxSize); // create the array



arr.insert(77); // insert 10 items

arr.insert(99);

arr.insert(44);

arr.insert(55);

arr.insert(22);

arr.insert(88);

arr.insert(11);

arr.insert(00);

arr.insert(66);

arr.insert(33);



arr.display(); // display items



arr.bubbleSort(); // bubble sort them



arr.display(); // display them again

} // end main()

} // end class BubbleSortApp

////////////////////////////////////////////////////////////////



The constructor and the insert() and display() methods of this class are similar to those we've seen before. However, there's a new method: bubbleSort(). When this method is invoked from main(), the contents of the array are rearranged into sorted order.



The main() routine inserts 10 items into the array in random order, displays the array, calls bubbleSort() to sort it, and then displays it again. Here's the output:



77 99 44 55 22 88 11 0 66 33

0 11 22 33 44 55 66 77 88 99



The bubbleSort() method is only four lines long. Here it is, extracted from the listing:



public void bubbleSort()

{

int out, in;



for(out=nElems-1; out>1; out--) // outer loop (backward)

for(in=0; in
if( a[in] > a[in+1] ) // out of order?

swap(in, in+1); // swap them

} // end bubbleSort()



The idea is to put the smallest item at the beginning of the array (index 0) and the largest item at the end (index nElems-1). The loop counter out in the outer for loop starts at the end of the array, at nElems-1, and decrements itself each time through the loop. The items at indices greater than out are always completely sorted. The out variable moves left after each pass by in so that items that are already sorted are no longer involved in the algorithm.



The inner loop counter in starts at the beginning of the array and increments itself each cycle of the inner loop, exiting when it reaches out. Within the inner loop, the two array cells pointed to by in and in+1 are compared, and swapped if the one in in is larger than the one in in+1.



For clarity, we use a separate swap() method to carry out the swap. It simply exchanges the two values in the two array cells, using a temporary variable to hold the value of the first cell while the first cell takes on the value in the second and then setting the second cell to the temporary value. Actually, using a separate swap() method may not be a good idea in practice because the function call adds a small amount of overhead. If you're writing your own sorting routine, you may prefer to put the swap instructions in line to gain a slight increase in speed.

Invariants



In many algorithms there are conditions that remain unchanged as the algorithm proceeds. These conditions are called invariants. Recognizing invariants can be useful in understanding the algorithm. In certain situations they may also be helpful in debugging; you can repeatedly check that the invariant is true, and signal an error if it isn't.



In the bubbleSort.java program, the invariant is that the data items to the right of out are sorted. This remains true throughout the running of the algorithm. (On the first pass, nothing has been sorted yet, and there are no items to the right of out because it starts on the rightmost element.)

Efficiency of the Bubble Sort



As you can see by watching the BubbleSort Workshop applet with 10 bars, the inner and inner+1 arrows make nine comparisons on the first pass, eight on the second, and so on, down to one comparison on the last pass. For 10 items, this is



9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 45



In general, where N is the number of items in the array, there are N-1 comparisons on the first pass, N-2 on the second, and so on. The formula for the sum of such a series is



(N–1) + (N–2) + (N–3) + ... + 1 = N*(N–1)/2



N*(N–1)/2 is 45 (10*9/2) when N is 10.



Thus, the algorithm makes about N2⁄2 comparisons (ignoring the –1, which doesn't make much difference, especially if N is large).



There are fewer swaps than there are comparisons because two bars are swapped only if they need to be. If the data is random, a swap is necessary about half the time, so there will be about N2⁄4 swaps. (Although in the worst case, with the initial data inversely sorted, a swap is necessary with every comparison.)



Both swaps and comparisons are proportional to N2. Because constants don't count in Big O notation, we can ignore the 2 and the 4 and say that the bubble sort runs in O(N2) time. This is slow, as you can verify by running the BubbleSort Workshop applet with 100 bars.



Whenever you see one loop nested within another, such as those in the bubble sort and the other sorting algorithms in this chapter, you can suspect that an algorithm runs in O(N2) time. The outer loop executes N times, and the inner loop executes N (or perhaps N divided by some constant) times for each cycle of the outer loop. This means you're doing something approximately N*N or N2 times.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...