Sorting Algorithms

 1. Bubble sort.

public static int bubble3(int[] arr) {
boolean swapped;
int count = 0;
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
count++;
if (arr[j] > arr[j + 1]) {
swapped = true;
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
if (!swapped) break;
}
return count;
}


2. Selection sort.

public static int selectionSort1(int[] arr) {
int count = 0;
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
count++;
if (arr[j] < arr[min]) {
min = j;
}
}
if (min != i) {
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
return count;
}


improved version:

public static int selectionSort2(int[] arr) {
int count = 0;
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i; j < n; j++) {
count++;
if (arr[j] < arr[min]) {
min = j;
}
}
if (min != i) {
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
} else {
break;
}
}
return count;
}


3. Insertion sort

public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int temp = arr[i];
int j = i;
while (j > 0 && arr[j - 1] > temp) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = temp;
}
}



public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j > 0; j--) {
if (arr[j] < arr[j - 1]) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
} else {
break;
}
}
}
}






































Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_11: Inheritance, Polymorphism

Preparation for Java interview