You are on page 1of 4

Sorting in Arrays

Selection sort :

public class SSort void printArray(int arr[])


{ {
void sort(int arr[]) int n = arr.length;
{ for (int i=0; i<n; ++i)
int n = arr.length; System.out.print(arr[i]+" ");
// One by one move boundary of unsorted subarray System.out.println();
for (int i = 0; i < n-1; i++) }
{
// Find the minimum element in unsorted array
public static void main(String[] args)
for (int j = i+1; j < n; j++)
{
{
SSort ob = new SSort();
if(arr[j]<arr[i])
int arr[] = {64,25,12,22,11};
{
ob.sort(arr);
int temp = arr[i];
System.out.println("Sorted array");
arr[i] = arr[j];
ob.printArray(arr);
arr[j] = temp;
}
} //main end
}
}
} //class end
}
Bubble Sort

public class BSort public static void main(String[] args)


{ {

BSort ob = new BSort();


void bubbleSort(int arr[]) int arr[] = {64, 34, 25, 12, 22, 11, 90};
{
ob.bubbleSort(arr);
int n = arr.length;
System.out.println("Sorted array");
for (int i = 0; i < n-1; i++)
ob.printArray(arr);
for (int j = 0; j < n-i-1; j++)
}
if (arr[j] > arr[j+1])

{
}
// swap arr[j+1] and arr[j]

int temp = arr[j];

arr[j] = arr[j+1];
Output

arr[j+1] = temp; Sorted array:

} 11 12 22 25 34 64 90

void printArray(int arr[])

int n = arr.length;

for (int i=0; i<n; ++i)

System.out.print(arr[i] + " ");

System.out.println();

}
Insertion Sort :

public class InSort public static void main(String[] args)

{ {

void sort(int arr[]) int arr[] = { 12, 11, 13, 5, 6 };

int n = arr.length; InSort ob = new InSort();

for (int i = 1; i < n; ++i) { ob.sort(arr);

int key = arr[i];

int j = i - 1; printArray(arr);

for(j=i-1;j >= 0 && arr[j] > key;j--) } //main end

{ } //class end

arr[j + 1] = arr[j];

arr[j + 1] = key;

} Output: 
 
static void printArray(int arr[])
5 6 11 12 13
{

int n = arr.length;

for (int i = 0; i < n; ++i)

System.out.print(arr[i] + " ");

System.out.println();

}
Quick Sort :
public class QSort static void quickSort(int[] arr, int low, int high)

{ {

static void swap(int[] arr, int i, int j) if (low < high)

{ {

int temp = arr[i]; int q = partition(arr, low, high);

quickSort(arr, low, q - 1);


arr[i] = arr[j];
quickSort(arr, q + 1, high);
arr[j] = temp;
}
}
}
static int partition(int[] arr, int low, int high)
static void printArray(int[] arr, int size)
{
{
int pivot = arr[high];
for(int i = 0; i < size; i++)
// Index of smaller element and
System.out.print(arr[i] + " ");
int i = (low - 1);

for(int j = low; j <= high - 1; j++)


System.out.println();
{
}
if (arr[j] < pivot) public static void main(String[] args)
{ {
i++; int[] arr = { 10, 7, 8, 9, 1, 5 };
swap(arr , i , j); int n = arr.length;

quickSort(arr, 0, n - 1);

} System.out.println("Sorted array: ");

swap(arr , i+1 , high); printArray(arr, n);

return(i+1); } //main end

}
} //class end

Output
Sorted array:
1 5 7 8 9 10

You might also like