Some sorting algorithms to learn
Sorting, could be defined as ordering a list of objects of any kind. There are two types of sorting; a) if the sorting is small enough, is called internal sorting and b) if the number is too big that part of the information has to be store on external storage, it is called external sorting.
Here, we are going to cover just 3 sorting algorithms that, in my understanding, are basic in every developers pocket.
1. Selection Sorting:
This sorting algorithm works by searching for the smallest element in the array and swapping it with the element in the first index of the array. Now the algorithm search for the smallest element in the remaining array (not taking into account the first index) and once it finds it, it swap it with the element in the second index.
This process is repeated until all the elements are organized in an ascending order from the first index to the final index.
To provide more context, let’s analyze the following “ar” array:
//Selection sort method
public static int[] selectionSort(int[] arr){
int[] num = arr;
for(int i=0;i<arr.length;i++){
int min= i;
for(int j = i+1;j<arr.length;j++){
if(num[j]<num[min]){
int temp = num[j];
num[j]=num[min];
num[min]=temp;
}
}
}
return num;
}//end of the selection sort method
2. Insertion Sorting:
This algorithm consist of advancing in pairs of two and swap the values in case the next one would be bigger than the previous one. For instance, see the following example:
//Insertion sort method
public static int[] insertionSort(int[] arr){
int[] num = arr;
for(int i=1;i<arr.length;i++){
int j= i;
while(j>0 && num[j-1]>num[j]){
int temp = num[j];
num[j] = num[j-1];
num[j-1] = temp;
j--;
}
}
return num;
}//end of the insertion sort method
3. Bubble Sorting:
This algorithm consist on comparing each element in the array with the object next to them. If happens that such element is bigger than the privous, it swap it. This algorithm repeats this process until the end of the array.
//Bucket sort method
public static int[] bubbleSorting(int[] arr){
int[] num = arr;
for(int i=arr.length;i>0;i--){
for(int j=1;j<i;j++){
if(num[j]<num[j-1]){
int temp = num[j];
num[j]= num[j-1];
num[j-1] = temp;
}
}
}
return num;
}//end of the bubble sort method
These are pretty basic sorting algorithms, but very handy when you would like to sort an array and you don't need to take into account many other variables.