Sort 2D array using insertion sort - java

I want to sort a 2D array of integers by a certain column using insertion sort. The following code works for 1D array.
private static void InsertionSort(int[] a, int n) {
int key, j;
for (int i = 1; i < n; i++){
key = a[i];
j = i - 1;
while ((j >= 0) && (a[j] > key)){
a[j+1] = a[j];
j = j - 1;
}
a[j+1] = key;
}
}
For 2D array, I specify an integer c for the column by which to sort the array. For example, if I sort by the first column,
{4, 1, 3},
{6, 0, 2},
{5, 9, 8}
becomes
{4, 1, 3},
{5, 9, 8},
{6, 0, 2}
This is what I got so far for sorting a 2D array by a specified column
private static void InsertionSort(int[][] a, int n, int c) {
in key, j;
for (int i = 1; i < n; i++){
key = a[i][c];
j = i - 1;
while ((j >= 0) && (a[j][c] > key)){
a[j+1][c] = a[j][c];
j = j - 1;
}
a[j+1][c] = key;
}
}
but the result for sorting by the first column is
{4, 1, 3}
{5, 0, 2}
{6, 9, 8}
It sorts the elements of the first column without keeping them together with their respective rows. How can I solve this?

You need to swap data row, not just the data element.
private static void sort(int[][] a, int n, int c) {
int key, j;
for (int i = 1; i < n; i++){
key = a[i][c];
int[] keyRow = a[i];
j = i - 1;
while ((j >= 0) && (a[j][c] > key)){
//a[j+1][c] = a[j][c];
a[j+1] = a[j];
j = j - 1;
}
//a[j+1][c] = key;
a[j+1] = keyRow;
}
}

From Java 8, you could do it in one line.
Arrays.sort(data, (a, b) -> a[COL] - b[COL]);
where COL is the column to sort.

Related

How to Insertion Sort?

What is missing?
less a little
It's almost done
Also is there a way to make it faster?
thanks
public class InsertionSort {
public static void main(String[] argv) {
int[] data = {4, 1, 7, 8, 9, 3, 2};
sort(data);
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
}
public static void sort(int[] data) {
int j, pivot;
// insert data[i] to sorted array 0 ~ i - 1
// begins from i = 1, because if the array has only one element then it must be sorted.
for (int i = 1; i < data.length; i++) {
pivot = data[i];
for (j = i - 1; j >= 0 && data[j] > pivot; j--) // shift data[j] larger than pivot to right
{
data[j+1] = data[j];
}
}
}
}
Your code have a problem when you are interchanging the values between data[j+1] and data[j]. You overwriting the value from data[j+1], without to keep it in a temporal variable and put it in data[j].
public class InsertionSort {
public static void main(String[] argv) {
int[] data = {4, 1, 7, 8, 9, 3, 2};
sort(data);
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
}
public static void sort(int[] data) {
int tmp, pivot;
// insert data[i] to sorted array 0 ~ i - 1
// begins from i = 1, because if the array has only one element then it must be sorted.
for (int i = 1; i < data.length; i++) {
pivot = data[i];
for (int j = i - 1; j >= 0 && data[j] > pivot; j--) // shift data[j] larger than pivot to right
{
tmp = data[j + 1];
data[j + 1] = data[j];
data[j] = tmp;
}
}
}
}
As #dan1st suggest, try to use quicksort if you want a better performance. A good explanation of the quicksort algorithm and it's Java implementation you could find here

grouping algorithm java n choose k

I have 10 numbers in a vector container contains: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. And I want n numbers in a group, for example:
n = 3
[1,2,3], [4,5,6], [7,8,9], [10]
[2,3,4], [5,6,7], [8,9,10], [1]
Is there an algorithm to find all the combinations?
int[] input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int k = 3;
List<int[]> subsets = new ArrayList<>();
int[] s = new int[k]; // here we'll keep indices
// pointing to elements in input array
if (k <= input.length) {
// first index sequence: 0, 1, 2, ...
for (int i = 0; (s[i] = i) < k - 1; i++);
subsets.add(getSubset(input, s));
for(;;) {
int i;
// find position of item that can be incremented
for (i = k - 1; i >= 0 && s[i] == input.length - k + i; i--);
if (i < 0) {
break;
}
s[i]++; // increment this item
for (++i; i < k; i++) { // fill up remaining items
s[i] = s[i - 1] + 1;
}
subsets.add(getSubset(input, s));
}
}
System.out.println();
for(int i = 0; i < subsets.size();i++) {
int[] result = subsets.get(i);
for(int j = 0; j < result.length; j++) {
System.out.print(result[j]+" ");
}
System.out.println();
}
}
int[] getSubset(int[] input, int[] subset) {
int[] result = new int[subset.length];
for (int i = 0; i < subset.length; i++)
result[i] = input[subset[i]];
return result;
}
Thank you.

remove number from array

I need to write a program which for a given array of ints prints all its elements, but each value only once, without repetitions. That is my tutor said. I agree that there are several example here, but I have special conditions like:
Do not create any auxiliary arrays, collections or Strings!
Do not use any classes from packages other than the standard java.lang.
I have been studying Java not so long so here is what I've done:
public class Third {
public static void main(String[] args) {
int[] p = {5, 2, 2, 5, -1, 5, 12, 2, 5, 44, 12, 9};
remove(p);
}
static public void remove(int[] a) {
int min = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
a[i] = min;
}
}
}
for (int j = 0; j < a.length; j++) {
if (a[j] != min) {
System.out.println( a[j] );
}
}
}
}
I realize that this is not efficient, because it is not able to print int's min value. So is there any other way to do it correctly ?
Since you said that you want to print the elements of the array only once, but you cannot use any structures or other arrays to achieve that, I believe your best strategy is to simply scan the array and look for elements with the same value from the index forward, and only print if you haven't found any.
For example: for the array {5, 2, 2, 5, -1, 5, 12, 2, 5, 44, 12, 9}, when you look at the first 5, you'll see three more fives to your right so you won't print anything, but when you look at that fourth 5, there'll be non and so you'll print it. When you see -1, for example, you won't see any other -1 to your right, and you'll print it.
public static void main(String[] args) {
int[] p = {5, 2, 2, 5, -1, 5, 12, 2, 5, 44, 12, 9};
remove(p);
}
static public void remove(int[] a) {
for (int i = 0; i < a.length; i++) {
boolean found = false;
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
found = true;
break;
}
}
if (!found)
System.out.println(a[i]);
}
}
And the output for your array will be:
-1
2
5
44
12
9
Every element is only printed once
Based on your question here i am providing solution. In this first i am sorting array in ascending order then i am printing current index a[i] if it is not equal to next index a[i+1] .
program:
int a[] = { 5, 2, 2, 5, -1, 5, 12, 2, 5, 44, 12, 9};
int temp = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i; j < a.length; j++)
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
for (int i = 0; i < a.length - 1; i++) {
if (a[i] != a[i + 1]) {
System.out.println(a[i]);
}
if (i == a.length - 2)
System.out.println(a[i + 1]);
}
output:
-1
2
5
9
12
44
Hope it will help you.

Java Selection Sort Modification

So I made this selection sort code, but I want it to increment one loop of the sort each time the function is called.
So I thought okay. Why not just remove the outer for loop and replace index with a static variable up top and increment it each time the function finishes its operations. But that just messed up the sort really badly. Can someone help?
Question: How do I go through the sort one step at a time each time the function is called?
I don't want it to sort the entire thing all at once
private static void selectionSort(int[] array) {
for (int index = 0; index < array.length; index++) {
int currentMin = array[index];
int indexOfMin = index;
for(int j = index+1; j < array.length; j++) {
if(array[j] < currentMin) {
currentMin = array[j];
indexOfMin = j;
}
}
swap(array, index, indexOfMin);
}
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
Why wouldn't global variable do the job? Do you wanna post your solution and we can take a look? Or you can also just pass the starting index to the function and call it with incremental index every time the button is pressed.
private static void selectionSort(int fromIndex, int[] array) {
int currentMin = array[fromIndex];
int indexOfMin = fromIndex;
for(int j = fromIndex+1; j < array.length; j++) {
if(array[j] < currentMin) {
currentMin = array[j];
indexOfMin = j;
}
}
swap(array, fromIndex, indexOfMin);
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
Then in main, call it like this:
for (int fromIndex = 0; fromIndex < array.length; fromIndex++) {
// Stop here and wait for button click.
selectionSort(fromIndex, array);
}
call function
Collections.sort(array, new SortData());
in SortData.java
import java.util.Comparator;
import tg.cw.pd.model.ModelcurrentMin;
public class SortData implements Comparator<Object>
{
public int compare(Object o1, Object o2)
{
int result;
String desc1 = ((ModelcurrentMin)o1).getcurrentMin();
String desc2 = ((ModelcurrentMin)o2).getcurrentMin();
result = desc1.compareTo(desc2); //asc
return result;
}
}
Check this one..
public static void main(String[] args) {
int[] array = new int[]{3, 4, 2, 7, 1, 5, 6};
System.out.println(Arrays.toString(array)); //[2, 4, 3, 7, 5, 1, 6]
selectionSort(array);
System.out.println(Arrays.toString(array)); //[1, 4, 3, 7, 5, 2, 6]
selectionSort(array);
System.out.println(Arrays.toString(array)); //[1, 2, 3, 7, 5, 4, 6]
selectionSort(array);
System.out.println(Arrays.toString(array)); //[1, 2, 3, 4, 5, 7, 6]
selectionSort(array);
System.out.println(Arrays.toString(array)); //[1, 2, 3, 4, 5, 6, 7]
}
private static void selectionSort(int[] array) {
for (int index = 0; index < array.length; index++) {
int currentMin = array[index];
int indexOfMin = index;
boolean swapNeeded = false;
for (int j = index + 1; j < array.length; j++) {
if (array[j] < currentMin) {
currentMin = array[j];
indexOfMin = j;
swapNeeded = true;
}
}
if (swapNeeded) {
swap(array, index, indexOfMin);
return;
}
}
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
selectionSort() has to be called 7 times to sort this array.
But if you consider array like {3, 5, 1, 4, 7, 6, 2}, 3rd and 4rd indices of the array are already in the sorted positions. Therefore, selectionSort() has to be called only 5 times.

Bubblesort doesn't sort properly

I have some code that I've compiled and ran. It is suppose to sort the values from smallest to greatest. Can someone help me find what is going on in the code and not making it sort correctly? I get these numbers
-9 -3 -1 1 6 7 83 19 2 6 4 6 32 66
Can someone help me and tell me what is wrong with the code? Thank you!
int myArray[] = {1, 6, -1, 7, 83, 19, -3, 6, 2, 4, 6, 32, 66, -9};
int n = myArray.length;
myArray = doop(myArray);
for (int i = 0; i < n; i++) {
System.out.println(myArray[i]);
}
private static int[] doop(int[] myArray) {
int n = myArray.length;
int swap;
for (int i = n - 1; i >= 0; i--) {
int j = i;
int min = myArray[i];
while ((j > 0) && (myArray[j - 1] < min)) {
myArray[j] = myArray[j - 1];
j = j - 1;
}
myArray[j] = min;
}
return myArray;
}
In bubble sort you have to compare the only the adjacent elements and traverse the array. Repeating this n-1 times , your array gets sorted and so correct code is:
private static int[] doop(int[] myArray)
{
int n = myArray.length;
for (int i = n - 1; i >= 0; i--)
{
for(int j=n-1;j>0;j--)
{
if(myArray[j]<myArray[j-1])
{
//swapping the elements
myArray[j]=myArray[j]^myArray[j-1];
myArray[j-1]=myArray[j]^myArray[j-1];
myArray[j]=myArray[j]^myArray[j-1];
}
}
}
return myArray;
}
int myArray[] = {1, 6, -1, 7, 83, 19, -3, 6, 2, 4, 6, 32, 66, -9};
int n = myArray.length;
myArray = doop(myArray);
for (int i = 0; i < n; i++) {
System.out.println(myArray[i]);
}
}
private static int[] doop(int[] myArray) {
int n = myArray.length;
int swap;
for (int i = n - 1; i >= 0; i--) {
int j = i;
int min = myArray[i];
while ((j > 0) && (myArray[j - 1] < min)) {
myArray[j] = myArray[j - 1];
j = j - 1;
myArray[j] = min;
}
}
return myArray;
}

Categories