Showing posts with label sorting. Show all posts
Showing posts with label sorting. Show all posts

Wednesday, 18 May 2011

Sorting an ArrayList in java

If the data in your ArrayList has a natural sorting order (ie, implements Comparable, as do String, Integer, ...), you can simply call the static Collections.sort() method. This is a stable, guaranteed n log n sort.
Collections.sort(yourArrayList);
If you want to choose a different sort criterion or your data doesn't implement xxxx, you will have to define a Comparator and pass that to the sort() method.
Collections.sort(yourArrayList, yourComparator);
Check out Collections for other useful utility methods.

Tuesday, 17 May 2011

Sorting an array in java

For sorting Arrays.sort(arr) is used, which is static function in arrays class.

Here a is array and method uses a tuned version of the QuickSort algorithm

int arr[] = {4,3,1};
Arrays.sort(arr);



This will sort the array in ascending order.


Seeing various sorting methods:


 

























Method
Arrays sort methods


Description


Arrays.sort(pa);

 


Sorts the elements of the array of a primitive type into ascending order using their natural ordering.


Arrays.sort(pa, from, to);


Sorts the elements pa[from]...pa[to-1] of a primitive type. into ascending order.


Arrays.sort(oa);


Sorts the elements of the array of an object type into ascending order, using the order defined by Comparable interface, which defines the compareTo method. Note that many Java classes such as String (but not StringBuffer), Double, BigInteger, etc implement Comparable.


Arrays.sort(oa, from, to);


Sorts the elements of the array, in the range from...to of an object type into ascending order.


Arrays.sort(oa, comp);


Sorts the elements of the array of an object type into ascending order, using the Comparator comp.


Arrays.sort(oa, from, to, comp);


Sorts the elements of the array, in the range from...to of an object type into ascending order using the Comparator comp.

Saturday, 14 May 2011

Collections.sort() vs Arrays.sort()

Difference between the Collections.sort() and Arrays.sort()?

Difference between the two is input. Collections.sort() has a input as List so it does a translation of List to array and vice versa which is an additional step while sorting. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have a array available with you and you want to sort it.

Algorithm – Algorithm seems to be same.

Saturday, 30 April 2011

Sorting an array using selection sort (java)

public static void main (String [] args) {
int n;
Scanner sc = new Scanner (System.in);
System.out.print ("Enter how many elements");
n = sc.nextInt();
int [] a = new int [n];

//input array
for (int i=0; i<n; i++){
System.out.print("Enter element " +(i+1) + " ");
a[i] = sc.nextInt();
}

//sorting
for (int i=0; i<n-1; i++) {
for (int j=i+1; j<n; i++) {
if(a[i]>a[j]){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}

//output
for (int i=0; i<n; i++){
System.out.println(a[i]);
}

}

Saturday, 25 September 2010

Inserting an Element into a Sorted Array

// Create anarray with an ordered list of items
String[] sortedArray = new String[]{"ant", "bat", "cat", "dog"};

// Search for a non-existent item and then insert it
int index = Arrays.binarySearch(sortedArray, "cow");
if (index < 0) { // Compute the insert index
    int insertIndex = -index-1; // Insert the new item into sortedArray. The example here creates
   // a new larger array to hold the new item.
   String[] newSortedArray = new String[sortedArray.length+1];
   System.arraycopy(sortedArray, 0, newSortedArray, 0, insertIndex);
    System.arraycopy(sortedArray, insertIndex, newSortedArray, insertIndex+1, sortedArray.length-insertIndex);
  newSortedArray[insertIndex] = "cow"
  sortedArray = newSortedArray;
}

Inserting an Element into a Sorted List in java

Although binarySearch() is used to locate existent elements, it can also be used to determine the insert index for non-existent elements. Specifically, the insertion index is computed in the following way: insert-index = (-return-value)-1

// Create a list with an ordered list of items
List sortedList = new LinkedList();

sortedList.addAll(Arrays.asList(new String[]{"ant", "bat", "cat", "dog"}));

// Search for the non-existent item
int index = Collections.binarySearch(sortedList, "cow"); // -4

// Add the non-existent item to the list
if (index < 0) { sortedList.add(-index-1, "cow"); }

Creating a Sorted Set

A sorted set is a set that maintains its items in a sorted order. Inserts and retrievals are more expensive in a sorted set but iterations over the set is always in order.

// Create the sorted set

SortedSet set = new TreeSet();

// Add elements to the set
set.add("b");
set.add("c");
set.add("a");

// Iterating over the elements in the set
Iterator it = set.iterator();
while (it.hasNext()) {
// Get element
Object element = it.next();
} // The elements are iterated in order: a, b, c

// Create an array containing the elements in a set (in this case a String array).
// The elements in the array are in order.
String[] array = (String[])set.toArray(new String[set.size()]);

Finding an Element in a Sorted Array

// Create an array with an ordered list of strings
String[] sortedArray = new String[]{"ant", "bat", "cat", "dog"};

// Search for the word "cat"
 int index = Arrays.binarySearch(sortedArray, "cat"); // 2

// Search for a non-existent element
index = Arrays.binarySearch(sortedArray, "cow"); // -4

Sorting a List

// Create a list
String[] strArray = new String[] {"z", "a", "C"};
List list = Arrays.asList(strArray);

// Sort
Collections.sort(list); // C, a, z

// Case-insensitive sort
Collections.sort(list, String.CASE_INSENSITIVE_ORDER); // a, C, z

// Reverse-order sort
Collections.sort(list, Collections.reverseOrder()); // z, a, C

// Case-insensitive reverse-order sort
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(list); // z, C, a

Tuesday, 21 September 2010

Arrays in java ( Sorting arrays in detail )

Why you shouldn't write your own sort

Good student problem. A favorite computer science topic it sorting, putting a collection of data in some order. Typically this is done for arrays. Textbooks cover both the slow, O(n2), sorts (eg, selection, insertion, and bubble sorts) and fast, O(n log n), sorts (quick sort, heap sort, etc). These are interesting problems, give students a lot of practice with arrays, bring up important tradeoffs, and are generally quite educational.
Bad professional pratice. However, the Java library already has sort methods that are more efficient, more general, and more correct than anything you are likely to write yourself. And they are already written. Professional programmers use one of the java.util.Arrays.sort() methods; they do not write their own, except perhaps in unusual cases.
Other data structures. There are sort methods in the java.util.Collections class which can be used to sort other kinds of data structures (eg, ArrayList), and there are data structures such as TreeMap that keep elements sorted based on a key.

Sorting Arrays with Arrays.sort(...)

The java.util.Arrays class has static methods for sorting arrays, both arrays of primitive types and object types. The sort method can be applied to entire arrays, or only a particular range. For object types you can supply a comparator to define how the sort should be performed.
MethodDescription
Arrays sort methods
Arrays.sort(pa);Sorts the elements of the array of a primitive type into ascending order using their natural ordering.
Arrays.sort(pa, from, to); Sorts the elements pa[from]...pa[to-1] of a primitive type. into ascending order.
Arrays.sort(oa);Sorts the elements of the array of an object type into ascending order, using the order defined by Comparable interface, which defines the compareTo method. Note that many Java classes such as String (but not StringBuffer), Double, BigInteger, etc implement Comparable.
Arrays.sort(oa, from, to); Sorts the elements of the array, in the range from...to of an object type into ascending order.
Arrays.sort(oa, comp);Sorts the elements of the array of an object type into ascending order, using the Comparator comp.
Arrays.sort(oa, from, to, comp); Sorts the elements of the array, in the range from...to of an object type into ascending order using the Comparator comp.

Example - Sorting arrays using Arrays.sort()

This example sorts an array of Strings and an array of doubles. All object types that implement Comparable (ie, defines compareTo() method), can be sorted with using a comparator. The Arrays.sort() method is also defined for primitive arrays.
1 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// File   : data-arrays/dblsort/Dblsrt.java
// Purpose: To show how Arrays.sort() works with arrays
// of both primitive and object values.
// Author : Fred Swartz 2006-08-23. Public domain.

import java.util.Arrays;

public class Dblsrt {
//========================================================= main
public static void main(String[] args) {
//... 1. Sort strings - or any other Comparable objects.
String[] names = {"Zoe", "Alison", "David"};
Arrays.sort(names);
System.out.println(Arrays.toString(names));

//... 2. Sort doubles or other primitives.
double[] lengths = {120.0, 0.5, 0.0, 999.0, 77.3};
Arrays.sort(lengths);
System.out.println(Arrays.toString(lengths));
}
}

Output from above program

[Alison, David, Zoe]
[0.0, 0.5, 77.3, 120.0, 999.0]

Comparators can define sort order

Java uses comparison sorts, which means that they make all ordering decisions by comparing two values. If there is no "natural" ordering, or you don't want to use it, you can specify a Comparator to use in comparing two values. See Comparators.

Sorting ArrayLists using Collections.sort(...)

In a similar way, you can use the methods below to sort ArrayLists.
Collections.sort(alist);
Collections.sort(alist, comparator);