Modified Bubble Sort - java

I need to write an algorithm that will take an array of ints and find the k'th largest element in the array. The caveat here is that the runtime must be O(K*n) or better.
My teacher has made it clear this can be done with a modified bubble sort program, but I am unsure as to how I can modify the bubble sort without ruining it, as I would think it necessary to loop through every element of the array. Here is my code (just the shell of the program and an unmodified bubble sort):
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
for (int i = (A.length - 1); i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (sorted[j-1] < sorted[j])
{
temp = sorted[j-1];
sorted[j-1] = sorted[j];
sorted[j] = temp;
}
}
}
return sorted[k-1];
}
Figured it out:
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
for (int i = 0; i < A.length-1; i++)
{
for (int j = 0; j < A.length-i-1; j++)
{
if (sorted[j] > sorted[j+1])
{
temp = sorted[j];
sorted[j] = sorted[j+1];
sorted[j+1] = temp;
}
if(i == (k-1)) return A[A.length-i-1];
}
}
return sorted[A.length-k];
}
The the array has been sorted to the k-th largest element, it has found what it is looking for and can stop the sort and return.

I thought a modified bubble sort just exited early if the list was already sorted?
Wouldn't something like this suffice?
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
bool bSorted = TRUE;
for (int i = (A.length - 1); i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (sorted[j-1] < sorted[j])
{
temp = sorted[j-1];
sorted[j-1] = sorted[j];
sorted[j] = temp;
bSorted = FALSE;
}
}
if(bSorted)
break;
}
return sorted[k-1];
}

Related

java - Selection Sort

I want to implement a selection alignment that receives 10 integers and organizes them in ascending order.
However, when my code is operated, other things work normally, but only the first integer is not aligned.
Please let me know how to fix the code.
public static void sort(int[] array) {
Scanner sc = new Scanner(System.in);
System.out.println("put the int");
for (int i =0;i <array.length;i++) {
System.out.print((i+1)+": ");
int n = sc.nextInt();
array[i] = n;
for (int j = 1; j < array.length;j++) {
if (array[i] < array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for (int a=0; a< array.length; a++) {
System.out.print(array[a]+" ");
}
}
public static void main(String[] args) {
int[] my_array = {0,0,0,0,0,0,0,0,0,0};
sort(my_array);
}
}
You should set
int j = 0
in the inner for
If you want to implement Selctionsort
initialize the inner for with int j = i+1
change numbers if array[i] is greater than array[j] not the other way around
for (int i =0;i <array.length;i++) {
int minValue = array[i];
for (int j = i +1; j < array.length;j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for (int a=0; a< array.length; a++) {
System.out.print(array[a]+" ");
}
You need to read the entire array in first, then you can sort it. Also, I don't consider your algorithm a true selection sort. In selection sort, you must find the minimum in the array of unsorted data. Then you swap. Your algorithm doesn't do that exactly.
To illustrate, I have broken the code into functions.
// Find the minimum value in the array, starting the search at "start"
// Returns the index of the minimum
static int findMinIndex(int[] array, int start)
{
int min = array[start];
int minIndex = start;
for (int i = start + 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
minIndex = i;
}
}
return minIndex;
}
// Swap 2 elements of an array
static void swap(int[] array, int index1, int index2)
{
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
// Selection sort the array, ascending
static void selectionSort(int[] array)
{
for (int i = 0; i < array.length; i++) {
// First find the minimum from i to the end of the array...
int minIndex = findMinIndex(array, i);
// ...then swap
if (minIndex != i) {
swap(array, i, minIndex);
}
}
}

Insertion sort array in java

So I made this sortion sort method, all using for loops.
I revised it on white board over and over, it looks perfect, however, when I implemented it, it keeps giving me wrong sort, but if I reversed the if condition, it will give me the right answer but in reverse, this doesn't make sense!
public void insertionSort(){
for (int i = 1; i < items.length; i++){
for (int j = 0; j < i; j++){
if (items[i] < items[j]) {
int temp = items[i];
shift(items,j, i-1);
items[j] = temp;
}
}
}
}
private void shift(int[] array, int index1, int index2){
if (index1 == index2)
array[index1 + 1] = array[index1];
else{
for (int i = index2; i >= index1; i--)
array[i+1] = array[i];
}
}
Thanks for the input, I discovered the problem in my Array class, it simply doubles the array size, my mistake was that I used the array.length instead of count.
public void insertionSort(){
for (int i = 1; i < count; i++){
for (int j = 0; j < i; j++){
if (items[i] < items[j]) {
int temp = items[i];
shift(items,j, i-1);
items[j] = temp;
}
}
}
}

Sort an array alphabetically

I need to sort book objects by their titles in a simple way. However, the selection sort algorithm I wrote isn't working properly and just moves the books around, but with no apparent order. What am I doing wrong?
int j;
int b;
for (int i = 0; i < 20 - 1; i++) {
int minIndex = i;
for (j = i + 1; j < 20; j++) {
b = (bookA[j].getTitle().compareTo(bookA[minIndex].getTitle()));
if (b < 0) {
minIndex=j;
}
}
Book temp = bookA[i];
bookA[i] = bookA[j];
bookA[j] = temp;
}
for (int z = 0; z < 20; z++)
System.out.println(bookA[z].toString());
You're using j as an index in bookA[i] = bookA[j];. The problem is that you're overriding the value of j at every iteration, so when it finally gets to bookA[i] = bookA[j]; it will always be 20.
What you want is to replace it with bookA[minIndex]. The resulting code would look like this:
int j;
int b;
for(int i=0;i<20-1;i++){
int minIndex=i;
for(j=i+1;j<20; j++) {
b=(bookA[j].getTitle().compareTo(bookA[minIndex].getTitle()));
if(b<0){
minIndex=j;
}
}
Book temp = bookA[i];
bookA[i] = bookA[minIndex];
bookA[minIndex] = temp;
}
for(int z=0;z<20;z++)
System.out.println(bookA[z].toString());

bubble sort with a boolean to determine whether array is already sorted

I have following code for bubble sort but its not sorting at all. if I remove my boolean then its working fine. I understand that since my a[0] is lesser than all other elements therefore no swapping is being performed can anybody help me with this.
package com.sample;
public class BubleSort {
public static void main(String[] args) {
int a[] = { 1, 2, 4, 5, 6, 88, 4, 2, 4, 5, 8 };
a = sortBuble(a);
for (int i : a) {
System.out.println(i);
}
}
private static int[] sortBuble(int[] a) {
boolean swapped = true;
for (int i = 0; i < a.length && swapped; i++) {
swapped = false;
System.out.println("number of iteration" + i);
for (int j = i+1; j < a.length; j++) {
if (a[i] > a[j]) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
swapped = true;
}
}
}
return a;
}
}
This is essentially the same as yours, but working and more efficient:
private static int[] bubblesort(int[] nums)
{
boolean done = false;
for (int i = 0; i < nums.length && !done; i++)
{
done = true;
for (int j = nums.length-1; j > i; j--)
{
if (nums[j] < nums[j-1])
{
int temp = nums[j];
nums[j] = nums[j-1];
nums[j-1] = temp;
done = false;
}
}
}
return nums;
}
At the end of the ith iteration, we know that the first i elements are sorted, so we don't need to look at them anymore. We need the boolean to determine if we need to continue or not. If no swaps are made, then we are done. We can remove the boolean and it will still work, but will be less efficient.
Your bubble sort is wrong?
private static int[] sortBuble(int[] a) {
boolean swapped = true;
int n = a.length;
for (int i = 0; i < n && swapped; i++) {
swapped = false;
int newn = 0;
System.out.println("number of iteration" + i);
for (int j = 1; j < a.length; j++) {
if (a[j-1] > a[j]) {
int temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
swapped = true;
newn = j;
}
}
n = newn;
}
return a;
}
It is called flagged bubble sort. It helps to save time mainly. It checks whether the array positions are sorted. if it is sorted it breaks, and move to 2nd execution.
and the code can be rewritten as:-
for (int j = 1; j < a.length; j++) {
if (a[j-1] > a[j]) {
int temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
swapped = true;
}
}
if(!swapped)
break;
}

having problems with mergesort algorithm

I am currently trying to transcribe a mergesort algorithm from a pseudocode level to a working implementation in java. This is my code
public int[] merge(int a[], int b[]) {
int c[] = new int[a.length + b.length];
int i = 0, j = 0;
for (int k = 0; k < c.length; k++) {
if (a[i] <= b[j]) {
c[k] = a[i++];
} else {
c[k] = b[j++];
}
}
return c;
}
The pseudocode interpretation is correct to the best of my knowledge but it keeps returning an ArrayOutofBound Exception.
Where did I get it all wrong.
This would obviously give the out of bound exception because you are not keeping track of the length of a and b arrays . Since k = a + b , a and b will always be less than k . Hence the exception.
And when you apply this check, remember to copy the remaining of the items, whether they are of a[] or b[] , to copy them to c[]. See this -
for(;i<a.length;i++)
c[k++] = a[i++];
for(;j<b.length;b++)
c[k++] = b[j++];
The merge algorithm in the way you intend to implement it is a bit more elaborated, below you'll find a correct implementation:
public int[] merge(int a[], int b[]) {
int i = 0, j = 0, k = 0;
int m = a.length, n = b.length;
int[] c = new int[m + n];
// Merge to the end of one of the source arrays
while (i < m && j < n) {
if (a[i] <= b[j]) {
c[k] = a[i];
i++;
} else {
c[k] = b[j];
j++;
}
k++;
}
// Determine which source array has elements remaining and
// append those to the result array
if (i < m) {
for (int p = i; p < m; p++) {
c[k] = a[p];
k++;
}
} else {
for (int p = j; p < n; p++) {
c[k] = b[p];
k++;
}
}
return c;
}

Categories