package com.lnn.sort;
import
java.util.Random;
public class Sorting {
private int array[];
private int size;
public Sorting(int size) {
this.size = size;
array = new int[10];
}
public void generate() {
Random
random = new Random();
for (int i = 0; i < size; i++) {
array[i] = random.nextInt(10) +
10;
}
}
public void display() {
for (int i = 0; i < size; i++) {
System.out.println("| " + i + " |
" + array[i] + " |");
}
}
public void bubbleSort() {
for (int i = size - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (array[j] > array[j + 1]) {
swap(j, j + 1);
}
}
}
}
public void selectionSort()
{
for (int i = 0; i < size; i++) {
int min = i;
for (int j = i; j < size; j++) {
if (array[min] > array[j]) {
min = j;
}
}
swap(i, min);
}
}
public void insertSort() {
for (int i = 1; i < size; i++) {
int j = i;
int insert = array[i];
while ((j > 0)
&& (array[j - 1] > insert)) {
array[j] = array[j - 1];
j--;
}
array[j] = insert;
}
}
public void shellSort() {
int inner, outer, temp;
int interval = 1;
while (interval <= size / 3) {
interval = interval * 3 + 1;
}
while (interval > 0) {
for (outer = interval; outer < size; outer++) {
temp = array[outer];
inner = outer;
while (inner > interval - 1 && array[inner - interval] >= temp) {
array[inner] = array[inner - interval];
inner -= interval;
}
array[inner] = temp;
}
interval = (interval - 1) / 3;
}
}
public void mergeSort(int min, int max) {
int less = min;
int high = max;
if (less >= high) {
return;
}
int middle = (less + high) / 2;
mergeSort(less, middle);
mergeSort(middle + 1, high);
int lessEnd = middle;
int highStart = middle + 1;
while ((min <= lessEnd) && (highStart <= high)) {
if (array[less] < array[highStart]) {
less++;
}
else {
int Temp = array[highStart];
for (int k = highStart - 1; k >= less; k--) {
array[k + 1] = array[k];
}
array[less] = Temp;
less++;
lessEnd++;
highStart++;
}
}
}
public void quickSort(int left, int right) {
if (right - left <= 0) {
return;
}
else {
int pivot = array[right];
int pivotIndex = partition(left, right, pivot);
quickSort(left, pivotIndex - 1);
quickSort(pivotIndex + 1, right);
}
}
private int partition(int left, int right, int pivot) {
int leftPointer = left - 1;
int rightPointer = right;
while (true) {
while (leftPointer < size - 1 && array[++leftPointer] < pivot)
;
while (rightPointer > 0
&& array[--rightPointer] > pivot)
;
if (leftPointer >= rightPointer) {
break;
}
else {
swap(leftPointer, rightPointer);
}
}
swap(leftPointer, right);
return leftPointer;
}
public void swap(int indexOne, int indexTwo) {
int temp = array[indexOne];
array[indexOne] = array[indexTwo];
array[indexTwo] = temp;
}
public static void main(String[] args) {
Sorting
sort = new Sorting(10);
sort.generate();
sort.mergeSort(0,
9);
sort.display();
}
}
No comments:
Post a Comment