Java: Sorting an array (Part 2) [duplicate] - java

This question already has answers here:
Java: Manipulating an Array
(5 answers)
Closed 9 years ago.
I understand how to sort an array by ascending and descending order, but there is a specific pattern I'm trying to create. For example, I have an array in a random order. How would I sort this array in the pattern? "smallest, largest, second smallest, second largest, thrid smallest, third largest..." etc Any ideas?
public class Test2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int[] array = {1,4,2,6,9,3,65,77,33,22};
for(int i = 0; i < array.length; i++){
System.out.print(" " + array[i]);
}
wackySort(array);
}
public static void wackySort(int[] nums){
int sign = 0;
int temp = 0;
int temp2 = 0;
//This sorts the array
for (int i = 0; i < nums.length; i++){
for (int j = 0; j < nums.length -1; j++){
if (nums[j] > nums[j+1]){
temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
// This prints out the new array
System.out.println();
for(int i = 0; i < nums.length; i++){
System.out.print(" " + nums[i]);
}
System.out.println();
//This part attempts to fix the array into the order I want it to
int firstPointer = 0;
int secondPointer = nums.length -1;
int[] newarray = new int[nums.length];
for (int i = 0; i < nums.length -1; i+=2){
newarray[i] = nums[firstPointer++];
newarray[i] = nums[secondPointer--];
}
for(int i = 0; i < newarray.length; i++){
System.out.print(" " + newarray[i]);
}
}
}

You need to write your own Comparator to achieve this. Study this article about Java Object Sorting Example (Comparable And Comparator). it will be helpful to you.

Related

The bubblesort is not sorting all the elements [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
I have a small question regarding this bubblesort algorithm below. I ran in VS, but its not giving me the sorted output, its just switching the places of the 2nd and the last element of the array. Can someone please look into it and debug it please?
import java.util.Arrays;
public class Arraysort {
static void sort(int[] array) {
int n = array.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n-i); j++) {
if (array[j-1] > array[i]) {
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
}
public static void main(String[] args){
int array[] = {2,6,7,9,5};
System.out.println("This is my unsorted Array\n");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
System.out.println();
}
sort(array);
System.out.println("This is my sorted Array\n");
for(int i = 0; i < array.length; i++) {
System.out.println(array[i] + " ");
}
}
}
Output is:
2
5
7
9
6
Well, this is because you have used the j range 1 to n-i. the problem here is when you use 1 to (n-i) it will skip one checking cycle of the list. So what you need to do is run algorithm n times (j < n ) in order to make sure you go through the all cycles in the list.
change j < (n-i) to j < (n)
public class Arraysort {
static void sort(int[] array) {
int n = array.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n); j++) {
if (array[j - 1] > array[i]) {
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
}
public static void main(String[] args) {
int array[] = { 2, 6, 7, 9, 5 };
System.out.println("This is my unsorted Array\n");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
System.out.println();
}
sort(array);
System.out.println("This is my sorted Array\n");
for (int i = 0; i < array.length; i++) {
System.out.println(array[i] + " ");
}
}
}

Using Bubble-Sort for Two-Dimensional Array in Java

I am looking to modify a bubble sort that I used for a one-dimensional array in order for it to sort a two-dimensional array. I honestly am just having a pretty hard time figuring out the necessary changes. My code is below.
Any help/feedback is appreciated, thanks!
int n;
int temp;
System.out.print("Please enter how large you want the array to be: ");
n = in.nextInt();
int sorting[] = new int[n];
System.out.println("Please enter the elements you want in the array: ");
for (int i = 0; i < n; i++)
{
sorting[i] = in.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (sorting[i] > sorting[j])
{
temp = sorting[i];
sorting[i] = sorting[j];
sorting[j] = temp;
}
}
}
System.out.print("Here is your array in ascending order: ");
for (int i = 0; i < n - 1; i++)
{
System.out.print(sorting[i] + ",");
}
System.out.print(sorting[n - 1]);

Reverse the rows of a 2d array

Yesterday I asked a very similar question and I kind of messed up with asking it.
I need to pass an array to a method and inside of that method I need to swap the rows around so if it's
1 2 3
3 2 1
2 1 3
it needs to be
3 2 1
1 2 3
3 1 2
With the code I have right now it swaps the last column to the first column spot correctly then it puts the column that's supposed to be last.
3 1 2
1 3 2
3 2 1
Also, it needs to stay a void because I need to be modifying the original array so I can't set it as a temp array but I can use a temp integer to store.
Here is the code I have right now that's sort of working
public static void reverseRows(int[][] inTwoDArray)
{
for (int row = 0; row < inTwoDArray.length; row++)
{
for (int col = 0; col < inTwoDArray[row].length; col++)
{
int tempHolder = inTwoDArray[row][col];
inTwoDArray[row][col] = inTwoDArray[row][inTwoDArray[0].length - 1];
inTwoDArray[row][inTwoDArray[0].length - 1] = tempHolder;
}
}
}
any help would be great, I'm running out of hair to pull out! Thanks!
First, how to reverse a single 1-D array:
for(int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
Note that you must stop in half of your array or you would swap it twice (it would be the same one you started with).
Then put it in another for loop:
for(int j = 0; j < array.length; j++){
for(int i = 0; i < array[j].length / 2; i++) {
int temp = array[j][i];
array[j][i] = array[j][array[j].length - i - 1];
array[j][array[j].length - i - 1] = temp;
}
}
Another approach would be to use some library method such as from ArrayUtils#reverse():
ArrayUtils.reverse(array);
And then again put into a cycle:
for(int i = 0; i < array.length; i++){
ArrayUtils.reverse(array[i]);
}
I guess this the easiest approach, tried and tested
For instance, you have
1 2
3 4
and you want
2 1
4 3
You can reverse the loop, without any extra space or inbuilt function.
Solution:
for(int i =0;i<arr.length;i++) //arr.length=no of rows
{
for(int j = arr[i].length-1;j>=0;j--)//arr[i].length=no of col in a ith row
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Not sure if I didn't confuse what array stores the rows and which one the columns.... but this should work (long time since I've done Java last, so be nice to me when spotting any errors please ^^):
public static void reverseRows(int[][] array)
{
for (int i = 0 ; i < array.length ; i++) { // for each row...
int[] reversed = new int[array[i].length]; // ... create a temporary array that will hold the reversed inner one ...
for(int j = 0 ; j < array[i].length ; j++) { // ... and for each column ...
reversed[reversed.length - 1 - j] = array[i][j]; // ... insert the current element at the mirrored position of our temporary array
}
array[i] = reversed; // finally use the reversed array as new row.
}
}
Java Code :-
import java.util.Scanner;
public class Rev_Two_D {
static int col;
static int row;
static int[][] trans_arr = new int[col][row];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
row = m;
int n = sc.nextInt();
col = n;
int[][] arr = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
arr[i][j] = sc.nextInt();
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length / 2; i++) {
int temp = arr[j][i];
arr[j][i] = arr[j][arr[j].length - i - 1];
arr[j][arr[j].length - i - 1] = temp;
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Reverse of two D array - Print your two D array in reverse order
public void reverse(){
int row = 3;
int col = 3;
int[][] arr = new int[row][col];
int k=0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++,k++) {
arr[i][j] = k;
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int i = arr.length -1; i >=0 ; i--) {
for (int j = arr.length -1; j >=0 ; j--) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int [][] a={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a.length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
System.out.println("***************************");
for(int i=0 ; i<a.length;i++)
{
for(int j=a.length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
}
Reverse 2 D Array
public static void main(String[] args) {
int a[][] = {{1,2,3},
{4,5,6},
{8,9,10,12,15}
};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a[i].length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
for(int i=0 ; i<a.length;i++)
{
for(int j=a[i].length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}

Java Array of unique randomly generated integers

public static int[] uniqueRandomElements (int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = (int)(Math.random()*10);
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
a[j] = (int)(Math.random()*10);
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
return a;
}
I have a method above which should generate an array of random elements that the user specifies. The randomly generated integers should be between 0 and 10 inclusive. I am able to generate random integers but the problem I have is checking for uniqueness. My attempt to check for uniqueness is in my code above but the array still contains duplicates of integers. What am I doing wrong and could someone give me a hint?
for (int i = 0; i < size; i++) {
a[i] = (int)(Math.random()*10);
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
a[j] = (int)(Math.random()*10); //What's this! Another random number!
}
}
}
You do find the duplicate values. However, you replace it with another random number that may be a duplicate. Instead, try this:
for (int i = 0; i < size; i++) {
a[i] = (int)(Math.random()*10);//note, this generates numbers from [0,9]
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
i--; //if a[i] is a duplicate of a[j], then run the outer loop on i again
break;
}
}
}
However, this method is inefficient. I recommend making a list of numbers, then randomizing it:
ArrayList<Integer> a = new ArrayList<>(11);
for (int i = 0; i <= 10; i++){ //to generate from 0-10 inclusive.
//For 0-9 inclusive, remove the = on the <=
a.add(i);
}
Collections.shuffle(a);
a = a.sublist(0,4);
//turn into array
Or you could do this:
ArrayList<Integer> list = new ArrayList<>(11);
for (int i = 0; i <= 10; i++){
list.add(i);
}
int[] a = new int[size];
for (int count = 0; count < size; count++){
a[count] = list.remove((int)(Math.random() * list.size()));
}
It might work out faster to start with a sequential array and shuffle it. Then they will all be unique by definition.
Take a look at Random shuffling of an array, and at the Collections.shuffle function.
int [] arr = [1,2,3,.....(size)]; //this is pseudo code
Collections.shuffle(arr);// you probably need to convert it to list first
If you have a duplicate you only regenerate the corresponding number once. But it might create another duplicate. You duplicate checking code should be enclosed in a loop:
while (true) {
boolean need_to_break = true;
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
need_to_break = false; // we might get another conflict
a[j] = (int)(Math.random()*10);
}
}
if (need_to_break) break;
}
But make sure that size is less than 10, otherwise you will get an infinite loop.
Edit: while the above method solves the problem, it is not efficient and should not be used for large sized arrays. Also, this doesn't have a guaranteed upper bound on the number of iterations needed to finish.
A better solution (which unfortunately only solves second point) might be to generate a sequence of the distinct numbers you want to generate (the 10 numbers), randomly permute this sequence and then select only the first size elements of that sequence and copy them to your array. You'll trade some space for a guarantee on the time bounds.
int max_number = 10;
int[] all_numbers = new int[max_number];
for (int i = 0; i < max_number; i++)
all_numbers[i] = i;
/* randomly permute the sequence */
for (int i = max_number - 1; i >= 0; i--) {
int j = (int)(Math.random() * i); /* pick a random number up to i */
/* interchange the last element with the picked-up index */
int tmp = all_numbers[j];
all_numbers[j] = a[i];
all_numbers[i] = tmp;
}
/* get the a array */
for (int i = 0; i < size; i++)
a[i] = all_numbers[i];
Or, you can create an ArrayList with the same numbers and instead of the middle loop you can call Collections.shuffle() on it. Then you'd still need the third loop to get elements into a.
If you just don't want to pay for the added overhead to ArrayList, you can just use an array and use Knuth shuffle:
public Integer[] generateUnsortedIntegerArray(int numElements){
// Generate an array of integers
Integer[] randomInts = new Integer[numElements];
for(int i = 0; i < numElements; ++i){
randomInts[i] = i;
}
// Do the Knuth shuffle
for(int i = 0; i < numElements; ++i){
int randomIndex = (int)Math.floor(Math.random() * (i + 1));
Integer temp = randomInts[i];
randomInts[i] = randomInts[randomIndex];
randomInts[randomIndex] = temp;
}
return randomInts;
}
The above code produces numElements consecutive integers, without duplication in a uniformly random shuffled order.
import java.util.Scanner;
class Unique
{
public static void main(String[]args)
{
int i,j;
Scanner in=new Scanner(System.in);
int[] a=new int[10];
System.out.println("Here's a unique no.!!!!!!");
for(i=0;i<10;i++)
{
a[i]=(int)(Math.random()*10);
for(j=0;j<i;j++)
{
if(a[i]==a[j])
{
i--;
}
}
}
for(i=0;i<10;i++)
{
System.out.print(a[i]);
}
}
}
Input your size and get list of random unique numbers using Collections.
public static ArrayList<Integer> noRepeatShuffleList(int size) {
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < size; i++) {
arr.add(i);
}
Collections.shuffle(arr);
return arr;
}
Elaborating Karthik's answer.
int[] a = new int[20];
for (int i = 0; i < size; i++) {
a[i] = (int) (Math.random() * 20);
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
a[i] = (int) (Math.random() * 20); //What's this! Another random number!
i--;
break;
}
}
}
int[] a = new int [size];
for (int i = 0; i < size; i++)
{
a[i] = (int)(Math.random()*16); //numbers from 0-15
for (int j = 0; j < i; j++)
{
//Instead of the if, while verifies that all the elements are different with the help of j=0
while (a[i] == a[j])
{
a[i] = (int)(Math.random()*16); //numbers from 0-15
j=0;
}
}
}
for (int i = 0; i < a.length; i++)
{
System.out.println(i + ". " + a[i]);
}
//Initialize array with 9 elements
int [] myArr = new int [9];
//Creating new ArrayList of size 9
//and fill it with number from 1 to 9
ArrayList<Integer> myArrayList = new ArrayList<>(9);
for (int i = 0; i < 9; i++) {
myArrayList.add(i + 1);
}
//Using Collections, I shuffle my arrayList
Collections.shuffle(myArrayList);
//With for loop and method get() of ArrayList
//I fill my array
for(int i = 0; i < myArrayList.size(); i++){
myArr[i] = myArrayList.get(i);
}
//printing out my array
for(int i = 0; i < myArr.length; i++){
System.out.print(myArr[i] + " ");
}
You can try this solution:
public static int[] uniqueRandomElements(int size) {
List<Integer> numbers = IntStream.rangeClosed(0, size).boxed().collect(Collectors.toList());
return Collections.shuffle(numbers);
}

sum of columns in a 2 dimensional array

static double [][] initialArray = {{7.432, 8.541, 23.398, 3.981}, {721.859, 6.9211, 29.7505, 53.6483}, {87.901, 455.72, 91.567, 57.988}};
public double[] columnSum(double [][] array){
int index = 0;
double temp[] = new double[array[index].length];
for (int i = 0; i < array[i].length; i++){
double sum = 0;
for (int j = 0; j < array.length; j++){
sum += array[j][i];
}
temp[index] = sum;
System.out.println("Index is: " + index + " Sum is: "+sum);
index++;
}
return temp;
}
public static void main(String[] args) {
arrayq test = new arrayq();
test.columnSum(initialArray);
}
I want to get the sum of all the columns, but I keep getting an outofbounds exception. This is the output I get:
Index is: 0 Sum is: 817.192
Index is: 1 Sum is: 471.18210000000005
Index is: 2 Sum is: 144.7155
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at NewExam.arrayq.columnSum(arrayq.java:11)
Your outer for loop condition is giving you problems. Here's your loop: -
for (int i = 0; i < array[i].length; i++)
Now, when i reaches the value 3, you are trying to access array[3].length. This will throw you IndexOutOfBounds exception.
Since the size of every internal arrays are same, you can change your loop to: -
for (int i = 0; i < array[0].length; i++)
Or, even better, just store the array[0].length in some variable before hand. But that will not make much of a difference.
I would also suggest you to use a better way to calculate the sum of columns. Avoid iterating over rows first. Keep the iteration a normal one probably like this: -
public double[] columnSum(double [][] array){
int size = array[0].length; // Replace it with the size of maximum length inner array
double temp[] = new double[size];
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
temp[j] += array[i][j]; // Note that, I am adding to `temp[j]`.
}
}
System.out.println(Arrays.toString(temp));
return temp; // Note you are not using this return value in the calling method
}
So, you can see that how your problem is highly simplified. What I did is, rather than assigning the value to the array, I added the new value of array[i][j] to the existing value of temp[j]. So, gradually, the value of array[i][j] for all i's (rows) gets summed up in temp[j]. This way you don't have to use confusing iteration. So, just add the above code to your method, and remove the old one.
This method will also work fine, even if you have jagged-array, i.e., you inner arrays are not of same size. But just remember to define the size of temp array carefully.
Also note that, I have used Arrays.toString(temp) method to print the array.
Problem with your code is when it tries to fetch arr[3].length as there does not exist simple solution like sum = sum+arr[i][j] where i refers to row and j refers to column.
int row = arr.length;
int col = arr[0].length;
for(int j = 0; j < cols; j++)
{
int sum = 0;
for(int i = 0; i < rows; i++)
{
sum = sum + input[i][j];
}
}
for (int i = 0; i < array[i].length; i++)
for(int i=0;i<size;i++)
i & size must never be change in the loop
So close. The problem is that you are using array[i].length in your for loop. I changed it from array[i].length to array[0].length and your problem is gone. You need j there but you don't actually HAVE it yet.
You COULD do something like this although there isn't really any point if you know how you are going to get your array. Differently sized lists still would break the code for calculating sum though, you'd have to change that as well.
for (int i = 0, j = 0; i < initialArray[j].length; i++) {
for (; j < initialArray.length; j++) {
System.out.println(i + " " + j);
}
j = 0;
}
And here is your modified program.
public class Main {
static double[][] initialArray = { { 7.432, 8.541, 23.398, 3.981 }, { 721.859, 6.9211, 29.7505, 53.6483 }, { 87.901, 455.72, 91.567, 57.988 } };
public double[] columnSum(double[][] array) {
int index = 0;
double temp[] = new double[array[index].length];
for (int i = 0; i < array[0].length; i++) {
double sum = 0;
for (int j = 0; j < array.length; j++) {
sum += array[j][i];
}
temp[index] = sum;
System.out.println("Index is: " + index + " Sum is: " + sum);
index++;
}
return temp;
}
public static void main(String[] args) {
new Main().columnSum(initialArray);
}
}
for index = 3, i is also equal with 3 and you have array[i].length in your code, but array have 3 item so you get Exception on array[3].length expression
try it
public double[] columnSum(double [][] array){
double temp[] = new double[array[0].length];
for (int i = 0; i < array[0].length; i++){
double sum = 0;
for (int j = 0; j < array.length; j++){
sum += array[j][i];
}
temp[i] = sum;
System.out.println("Index is: " + i + " Sum is: "+sum);
}
return temp;
}

Categories

Resources