Sorting of array can be done through various logic's!! Either through using Arrays.sort() method or through customize logic. Here we are going to discuss the customized logic. Below is the logic snippet for sorting the elements of an integer array
Logic for custom sort:
for(int i=0;i<size-1;i++)
{
for(int j=0;j<size-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
use of sort method:
Arrays.sort(arr);
Complete Code:
class SortingArray {
public void customSort(int [] arr)
{
int size=arr.length;
int temp=0;
// outer loop
for(int i=0;i<size-1;i++)
{
// inner loop
for(int j=0;j<size-1;j++)
{
if(arr[j]>arr[j+1])
{
/*
* Swapping logic
*/
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
// displaying the elements of the array
for(int i=0;i<size;i++)
{
System.out.println(arr[i]);
}
}
}
public class TestSortingArray {
public static void main(String[] args) {
// creating an object of SortingArray
SortingArray sortingArray = new SortingArray();
// invoke the method customSort and pass the array
sortingArray.customSort(new int[] { 9, 3, 2,2, 5, 4 });
}
}
# For using sort method in the above code, replace the outer and inner loop with Arrays.sort(arr)
Input Array: 9,3,2,2,5,4
Output:
Comments
Post a Comment