Generally, there are two types of Sorting in Java, they are,
1.Selection Sort
2.Bubble Sort
Watch this video tutorial about Sorting in Java
Subscribe to me on Youtube for more videos!
1.Selection Sort
class SelectionSort
{
static void test()
{
int[] arr = {1,5,45,23,47,25,45}; //initializing an integer type array
int n = 7; //n = no. of elements in the array
for(int i = 1;i<=n;i++) //performing the logic ‘n’ types
{
for(int j=0;j<(n-1);j++)
{
int a = arr[j]; //storing the element at ‘j’ th position in the variable ‘a’
int k = j+1; //keeping the value of ‘k’ ahead of one position with respect to ‘j’
int b = arr[k]; //storing the element at ‘k’ th position in the variable ‘b’
if(b<a) //if the condition is satisfied, then control goes inside the loop
{ //exchanging the positions of the elements of array.
int temp1=a; //storing the value of a in temporary variable temp1
int temp2=b; //storing the value of a in temporary variable temp2
arr[j] = temp2; //replacing the existing element at ‘j’ th postion with the new integer element ‘temp2’
arr[j+1] = temp1; //replacing the existing element at ‘j+1’ th postion with the new integer element ‘temp2’
}
}
}
for(int d = 0;d<7;d++) //Printing out the sorted array in ascending order
System.out.print(arr[d]+ ” “);
}
}
2.Bubble Sort
class BubbleSort
{
static void test()
{
int arr[] = {23,58,47,2,156,847,12}; //intializing an integer type array array
int n = 7; //n = no of elements in the array
System.out.println(“The Sorted Array is “);
for(int i=0;i<=(n-1);i++) //Iterating the logic (n-1) times
{
for(int j=0;j<6;j++) //Making changes with the array
{
int k = j+1;
int a = arr[j];
int b = arr[k];
if(b<a) //Comparing adjacent elements of the array
{
int temp1 = a; //storing the value of a in temp1
int temp2 = b; //storing the value of b in temp2
arr[j] = b; //exchanging posistions
arr[k] = a; //exchanging posistions
}
}
}
for(int d = 0;d<7;d++) //Printing the sorted array
System.out.print(arr[d]+” “);
}
}
Hey !
Create your First Android Application with Java now!
This is not included in ICSE syllabus and it is no where near the ICSE prescribed syllabus actually. However, you can still learn it if you are very much interested in Java and if you would love to create Applications.