You are on page 1of 3

//SOUVIK & SOUMODIP

A program to sort an array without swapping elements.

import java.io.*;
public class SortWithoutUsingAnyMemory
{
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the length of the array");
int n=Integer.parseInt(br.readLine());
int unsorted[]=new int[n],x[]=new int[n];
for(int i=0;i<n;i++)
{
System.out.print("Enter the element for unsorted["+i+"]");
unsorted[i]=Integer.parseInt(br.readLine());
}
x=sort(unsorted,0);
System.out.println("The sorted array is as follows");
for(int i=0;i<n;i++)
System.out.print(x[i]+" ");
}
public static int[] sort(int[] array, int start)
{
while(start < array.length)
{
if(start < 1)
start = 1;
if(array[start] < array[start-1])
{
array[start] += array[start-1];
array[start-1] = array[start] - array[start-1];
array[start] = array[start] - array[start-1];
start--;
}
else
{
start++;
}
}
return array;
}
}
SAMPLE OUTPUT:

Enter the length of the array


5
Enter the element for unsorted[0]5
Enter the element for unsorted[1]6
Enter the element for unsorted[2]8
Enter the element for unsorted[3]1
Enter the element for unsorted[4]4
The sorted array is as follows
14568

You might also like