Sorting of an array without using sort method in java is most popular in interview. so here is the solution.
first i am taking an int type array a now for each loop is to printing the array
(you can skip this loop its not important.).
now take an int temp which will store the value for temprary.
now for loop wil be start from index 0 to length-1 inside this for loop another
loop will be start from 0 to length of array-2 .
now in the if condition it will check if (a[j]<a[j+1] ) if this condition will be true than
in temp value of a[j] will be store and a[j] will store value ofa[j+1].
in this step no. will swap according to value .
public class CustomSorting {
public static void main(String[] args) {
int [] a={7,45,36,64,77,34,72,95};
for(int no:a)
{
System.out.println("before sorting "+no);
}
//temp store value temprary
int temp;
for(int i=0; i<=a.length-1;i++)
{
for( int j=0; j<=a.length-2;j++)
{
if(a[j]<a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println(" .......... ");
for(int no:a)
{
System.out.println(" after sorting "+no);
}
}
}
}
first i am taking an int type array a now for each loop is to printing the array
(you can skip this loop its not important.).
now take an int temp which will store the value for temprary.
now for loop wil be start from index 0 to length-1 inside this for loop another
loop will be start from 0 to length of array-2 .
now in the if condition it will check if (a[j]<a[j+1] ) if this condition will be true than
in temp value of a[j] will be store and a[j] will store value ofa[j+1].
in this step no. will swap according to value .
public class CustomSorting {
public static void main(String[] args) {
int [] a={7,45,36,64,77,34,72,95};
for(int no:a)
{
System.out.println("before sorting "+no);
}
//temp store value temprary
int temp;
for(int i=0; i<=a.length-1;i++)
{
for( int j=0; j<=a.length-2;j++)
{
if(a[j]<a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println(" .......... ");
for(int no:a)
{
System.out.println(" after sorting "+no);
}
}
}
}