Sorting an array of integers in java
In computer science and mathematics, a sorting algorithm is an algorithm that puts elements of a list in a certain order.
Summaries of popular sorting algorithms
Summaries of popular sorting algorithms
- Bubble sort
- Insertion sort
- Shell sort
- Merge sort
- Heap sort
- Quick sort
- Bucket sort
- Radix sort
- Distribution sort
- Shuffle sort
public class SortNumbers {
public static void sort(int[] nums) {
for (int i = 0; i < nums.length; i++) {
int min = i;
for (int j = i; j < nums.length; j++) {
if (nums[j] < nums[min])
min = j;
}
int tmp;
tmp = nums[i];
nums[i] = nums[min];
nums[min] = tmp;
}
}
public static void main(String[] args) {
int[] nums = new int[args.length]; // Create an array to hold numbers
for (int i = 0; i < nums.length; i++)
nums[i] = Integer.parseInt(args[i]);
sort(nums); // Sort them
for (int i = 0; i < nums.length; i++)
// Print them out
System.out.println(nums[i]);
}
}
Compile it as:
javac SortNumbers.java
java SortNumbers 45 89 21 74 15 -1 25 7
The output will be as:
-1
7
15
21
25
45
74
89
Comments
Post a Comment