Java exercises and solutions: array sort


Java arrays

Exercise 1: By using the bubble sort algorithm, write a Java program to sort an integer array of 10 elements in ascending.

Solution:

public class BubbleSort {

public static void main(String[] args){
//unsorted array
int[] arr={12,34,23,2,4,56,80,34,45,90};
//sorted array using bubble sort
bubblesort(arr,arr.length);
//display the content of sorted array
int i;
for(i=0;i<arr.length;i++) System.out.println(arr[i]);

}

public static void bubblesort(int[] dataset, int n){
int i,j;
for(i=0;i<n;i++)
for(j=n-1;j>i;j--)
if(dataset[j]<dataset[j-1])
{
int temp=dataset[j];
dataset[j]=dataset[j-1];
dataset[j-1]=temp;
   
}

 
}

}

Exercise 2: Modify the Java code in exercise 1 to sort the array in descending order.

Solution:

public class BubbleSort {

public static void main(String[] args){
//unsorted array
int[] arr={12,34,23,2,4,56,80,34,45,90};
//sorted array using bubble sort
bubblesort(arr,arr.length);
//display the content of sorted array
int i;
for(i=0;i<arr.length;i++) System.out.println(arr[i]);

}

public static void bubblesort(int[] dataset, int n){
int i,j;
for(i=0;i<n;i++)
for(j=n-1;j>i;j--)
if(dataset[j]>dataset[j-1])
{
int temp=dataset[j];
dataset[j]=dataset[j-1];
dataset[j-1]=temp;
   
}

 
}

}



Comments

thambidurai comment

 thambidurai

Java program to subtract the following array inputs, a[5] = { 0 , 4 , 6 , 8 , 10} b[6] = {3 , 2 , 11 , 8 , 4}


2017-06-12



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.