MainMenu

Home Core Java Overview Maven Tutorials

Friday, 22 December 2017

Sort the array without using Java functions


Hello friends,

In this article we will learn how to sort the Array with java Collection and Without using java function



So first let's discuss by using java Method :
Sort the array by using java function.

public class Arraysort
{
public static void main(String args[])
{
int[] ary = {25, 32, 1, 6, 11, 9, 17, 100, 95};
Arrays.sort(ary);
System.out.println("Sorted array is : %s", Arrays.toString(ary));
}
}

Note : By default array will be sorted in ascending order.

Sort the array in descending order :

public class Arraysort
{
public static void main(String args[])
{
int[] ary = {25, 32, 1, 6, 11, 9, 17, 100, 95};
Arrays.sort(ary, Collections.reverseOrder());
System.out.println("Sorted array is : %s ", Arrays.toString(ary) );
}
}

Sort the String array in Ascending & descending array

public class Arraysort
{
public static void main(String args[])
{
int[] ary = {"way2testing.com", "datastop.in", "onlineifsccodebank.com"};
System.out.println("Sorted array is : %s \n\n", Arrays.toString(ary) );
}
}

Sort the string array in decending order
public class Arraysort
{
public static void main(String args[])
{
int[] ary = {"way2testing.com", "datastop.in", "onlineifsccodebank.com"};
Arrays.sort(ary, Collections.reverseOrder());
System.out.println("Sorted array in decending order is : %s ", Arrays.toString(ary) );
}
}

Sort the String without using Java API

Sort the String without using Java API
public class SortString
{
public static void main(String args[])
{
char temp;
String modifiedString = "";
Scanner userstring = new Scanner(System.in);
System.out.println("Enter your String");
String str = userstring.next();
}
char[] chrary = str.toCharArray();
for(int i = 0; i<chrary.length; i++)
{
for(int j = 0; j<chrary.length; j++)
{
if(chrary[i]<chrary[j])
{
temp = chrary[i];
chrary[i] = chrary[j];
chrary[j] = temp;
}
}
}
for(int k = 0; k<chrary.length; k++)
{
modifiedString = modifiedString + chrary[k];
}
System.out.println("Your sorted string is : " +modifiedString);
}



How to sort an array without using sort function in java.

public class sortme
{
public static void main(String args[])
{
int[] ary = {25, 3, 29, 9, 15, 40, 90, 75};
for(int i =0; i<ary.length; i++)
{
for(int j =0; j<ary.length; j++)
{
if(ary[i]<ary[j])
{
temp = ary[i];
ary[i] = ary[j];
ary[j] = temp;
}
}
}
for(int k = 0; k<ary.length; k++)
{
System.out.println("Your sorted array is : " +ary[k]);
}
}
}

No comments:

Post a Comment