A sorting algorithm is an algorithm that orders a specific data structure, such as lists and trees.
A few sorting algorithms are:
- bubble sort, O(n2)
- insertion sort, O(n2)
- quicksort, O(n log n)
- selection sort, O(n2)
- merge sort, O(n log n)
Examples
Java
(built-in) To be able to sort objects of some arbitrary class you will need to provide a comparator to the sort method.
Array
you need to import java.util.Arrays to sort arrays
import java.util.Arrays;
public class Sort {
// define main method of this java code
public static void main(String[] args){
// declare an array named intArray for integer type values
int[] intArray = {15,17,14,20};
Arrays.sort(intArray);
}
}
List
You need to import java.util.Collections to sort Lists
import java.util.Collections;
public class Sort {
// define main method of this java code
public static void main(String[] args){
// declare an array named intArray for integer type values
int[] intArray = {15,17,14,20};
List list = Arrays.asList(intArray);
Collections.sort(list)
}
}
|