Home Programming Java Array Programs Part-1 (Sorting Techniques) (ICSE computer Applications)

Array Programs Part-1 (Sorting Techniques) (ICSE computer Applications)

0
1193

 

Array Programs:-  Array is a collection of same type of data elements. In java an array can only store same type of data(int, float,double,long,String, any type of object). The size of the array has to be declared before creating or while creating an array. One created the size of the array can’t be changed. For sorting the array there are many types of methods. One of them is bubble sort.

Bubble sort:- 

import java.io.*;
class Bubblesort
{
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“enter the length of the array”);
int len=Integer.parseInt(br.readLine());
int arr[]=new int[len];
int temp=0;
for(int i=0;i<len;i++)
{
System.out.println(“enter the elements”);
arr[i]=Integer.parseInt(br.readLine());
}
for(int i=0;i<len;i++)
{
for(int j=0;j<len-i-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
System.out.println(“The sorted array elements are”);
for(int i=0;i<len;i++)
{
System.out.println(arr[i]);
}
}
}

Output:-

enter the length of the array
5
enter the elements
67
enter the elements
2
enter the elements
1
enter the elements
89
enter the elements
4
The sorted array elements are
1
2
4
67
89

2. Selection Sort:-

import java.io.*;
class Selectionsort
{
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“enter the length of the array”);
int len=Integer.parseInt(br.readLine());
int arr[]=new int[len];
int temp=0;
for(int i=0;i<len;i++)
{
System.out.println(“enter the elements”);
arr[i]=Integer.parseInt(br.readLine());
}
System.out.println(“Before Selection Sort”);
for (int i=0;i<arr.length;i++)
System.out.print(“\t”+ arr[i]);
System.out.println();
for (int i = 0; i<arr.length – 1; i++)
{
int index = i;
for (int j = i + 1; j <arr.length; j++){
if (arr[j] <arr[index]){
index = j;
}
}
int small_Num = arr[index];
arr[index] = arr[i];
arr[i] = small_Num;
}
System.out.println(“after Selection Sort”);
for (int i=0;i<arr.length;i++)
System.out.print(“\t”+ arr[i]);
System.out.println();
}
}

 

 

Output:-

enter the length of the array

5

enter the elements

23

enter the elements

7

enter the elements

89

enter the elements

4

enter the elements

2

Before Selection Sort

23 7 89 4 2

after Selection Sort

2 4 7 23 89

 

NO COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here