Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Heapsort java #189

Closed
wants to merge 7 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions heapsort/Java/heapsort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
public class ExampleHeapSort {
public static void main(String[] args) {
int[] numbers = { 14, 6, 9, 4, 56, 34, 21, 39 };
heapsort(numbers);
for (int h = 0; h < numbers.length; h++)
System.out.print(numbers[h]+ " ");
}

public static void heapsort(int[] a) {
for (int i = a.length / 2 - 1; i >= 0; i--)
shiftDown(a, i, a.length);
for (int i = a.length - 1; i > 0; i--) {
swap(a, 0, i);
shiftDown(a, 0, i);
}
}

private static void shiftDown(int[] a, int i, int n) {
int child;
int tmp;

for (tmp = a[i]; leftChild(i) < n; i = child) {
child = leftChild(i);
if (child != n - 1 && (a[child] < a[child + 1]))
child++;
if (tmp < a[child])
a[i] = a[child];
else
break;
}
a[i] = tmp;
}

private static int leftChild(int i) {
return 2 * i + 1;
}

public static void swap(int[] numbers, int i, int j) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}