I am just sorting an array and need some advice on the sorting and I also need help printing the array after I have sorted it. Also no, I do not want to use the Arrays utility.
Code:
package Sort;
public class SortCode {
static int[] intArray = {
12, 34, 99, 1, 89,
39, 17, 8, 72, 68};
int j = 0;
int i = 0;
void printArray(int[] arrayInts) {
System.out.println("Values before sorting:");
System.out.println("Index" + "\tValue");
for (; j < arrayInts.length; j++) {
System.out.println(j + "\t" + arrayInts[j]);
} //for (int j)
} //void printArray
void sortArray() {
System.out.println("Values after sorting:");
System.out.println("Index" + "\tValue");
int i;
int k;
for (i = 0; i < intArray.length; i++) {
for (k = 0; k > intArray.length; k++) {
if (intArray[i] > intArray[k]) {
int firstNum = intArray[i];
int secondNum = intArray[k];
intArray[i] = secondNum;
intArray[k] = firstNum;
} //if
} //for
} //for
} //void sortArray
} //class BranchCode
Change sign > for < inside for (k = 0; k > intArray.length; k++) {
Probably it should help you
You would be able to find different sorting implementation on mathbits http://mathbits.com/MathBits/Java/arrays/Sorting.htm .
Here is better example of bubble sort .
public void bubbleSort(int[] array) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}
This might help as well Java: Sort an array
Example to use code
public class SortExample {
int[] intArray = { 12, 34, 99, 1, 89, 39, 17, 8, 72, 68 };
public void printArray(int[] arrayInts) {
for (int j = 0; j < arrayInts.length; j++) {
System.out.println(j + "\t" + arrayInts[j]);
} // for (int j)
} // void printArray
public void bubbleSort(int[] array) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}
public void process() {
System.out.println("Values before sorting:");
System.out.println("Index \tValue");
printArray(intArray);
bubbleSort(intArray);
System.out.println("Values after sorting:");
System.out.println("Index" + "\tValue");
printArray(intArray);
}
public static void main(String[] args) {
SortExample example = new SortExample();
example.process();
}
}
Related
I am trying to get an output of [4,6,6,7] with length 4 where arr[i] <= arr[i+1] where it is non-decreasing and it is contiguous. I know what i have to do but i dont know how to do it. my code prints out [3,4,6,6,7]. I am just having trouble on the contiguous part, any help? im not allowed to use extra arrays.
public static void ascentLength(int arr[], int size) {
int length = 0;
int index = 0;
int count = 1;
for (int i = 0; i < size-1; i++) {
index = i;
if (arr[0] <= arr[i+1] && count >0) {
System.out.println(arr[i]+ " index:" + index);
length++;
count++;
}
if (arr[0] >= arr[i+1]) {
}
}
System.out.println("length: " + length);
}
/* Driver program to test above function */
public static void main(String[] args) {
int arr[] = {5, 3, 6, 4, 6, 6, 7, 5};
int n = arr.length;
ascentLength(arr, n);
}
Here is my solution, it would be easier, if you could work with List, but this works for arrays:
public static void ascentLength(int arr[], int size) {
if(size == 1) System.out.println("length: 1");
// variables keeping longest values
int longestStartingIndex = 0;
int longestLength = 1;
// variables keeping current values
int currentStartingIndex = 0;
int currentCount = 1;
for (int i = 1; i < size; i++) {
if (arr[i-1] <= arr[i]) {
currentCount++;
} else {
// check if current count is the longest
if(currentCount > longestLength) {
longestLength = currentCount;
longestStartingIndex = currentStartingIndex;
}
currentStartingIndex = i;
currentCount = 1;
}
}
if(currentCount > longestLength) {
longestLength = currentCount;
longestStartingIndex = currentStartingIndex;
}
}
I've attempted to code an Insertion Sort in java via pseudo code from a book. The output for this code should be numbers in ascending order but for some reason I get 10,4,5,6,7,8,9. Any help is greatly appreciated! Thanks!
public class InsertionSort {
public int Array[] = {10,9,8,7,6,5,4};
public static void main(String[] args) {
InsertionSort obj1 = new InsertionSort();
}
public InsertionSort() {
InsertionSortMethod();
PrintArray();
}
public void InsertionSortMethod() {
for(int j = 2; j < Array.length; j++) {
int key = Array[j];
int i = j - 1;
while(i > 0 && Array[i] > key) {
Array[i + 1] = Array[i];
i = i - 1;
}
Array[i + 1] = key;
}
}
public void PrintArray() {
for(int i = 0; i < Array.length; i++) {
System.out.println(Array[i]);
}
}
}
Start the for loop from j=1 like this :
for(int j = 1; j < array.length; j++) {
and modify while loop condition like this:
while(i >= 0 && array[i] > key) {
Correct working code :
public class InsertionSort {
public int array[] = {10,9,8,7,6,5,4};
public static void main(String[] args) {
InsertionSort obj = new InsertionSort();
obj.insertionSortMethod();
obj.printArray();
}
public void insertionSortMethod() {
for(int j = 1; j < array.length; j++) {
int key = array[j];
int i = j - 1;
while(i >= 0 && array[i] > key) {
array[i + 1] = array[i];
i = i - 1;
}
array[i + 1] = key;
}
}
public void printArray() {
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}
At the third line of your code i.e.,
InsertionSort obj1 = new InsertionSort();
You are making an object of InsertionSort class but in your code, it is defined as a function I think it is a constructor you must mention the class for more convenience of the reader.
Apart from that, you are starting your loop with 2 for(int j = 2; j < Array.length; j++)
why so? your one element got missed so start j with 1
:)
Thanks to all the answers. I have also found by tracing the algorithm that flipping the second 'greater than' sign to a 'less than' sign on the 5th line of the algorithm does the trick for working in descending order. This may possibly be a typo in the book i'm reading. Thanks again!
try this method
public int[] insertionSort(int[] list) {
int i, j, key, temp;
for (i = 1; i < list.length; i++) {
key = list[i];
j = i - 1;
while (j >= 0 && key < list[j]) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
j--;
}
}
return list;
}
package com.borntoinnovation.datastructure;
import java.util.Arrays;
public class SortingInsertion {
public static void main(String[] args) {
int[] array = new int[] { 4, 3, 2, 20, 12, 1, 5, 6 };
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < i; j++) {
if (array[i] < array[j]) {
int temp = array[i];
for (int k = i; k > j; k--) {
array[k] = array[k - 1];
}
array[j] = temp;
}
}
System.out.println(Arrays.toString(array));
}
}// end of main()
}
My task is to write a function that rearranges an array so that the odd numbers occur in the beginning of the array, from greatest to least, and the even numbers from least to greatest at the end. We are not allowed to use any other libraries except for the standard input and output streams.
The output works when the numbers are:
{-15, 450, 6, -9, 54}
But if I changed the elements to:
{-55, 45, 6, 11, 54}
There is an exception error. Here is my code:
public class ary1 {
public static void sort(int A[], int n) {
int tmp;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (A[0] % 2 == 0) //even
{
if (A[i] < A[j]) {
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
} else {
if (A[i] > A[j]) {
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
}
}
}
public static void showAray(int A[], int n) {
for (int i = 0; i < n; i++) {
System.out.println(A[i]);
}
}
public static void main(String args[]) {
int array1[] = {-55, 45, 6, 11, 54};
int odd = 0;
int even = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] % 2 == 0) {
even++;
} else {
odd++;
}
}
int[] array2 = new int[even];
int[] array3 = new int[odd];
for (int i = 0, j = 0, k = 0; i < array1.length; i++) {
if (array1[i] % 2 == 0) {
array2[j++] = array1[i];
} else {
array3[k++] = array1[i];
}
}
System.out.println("Original array:\n");
showAray(array1, array1.length);
sort(array2, even);
sort(array3, odd);
for (int i = 1; i < array1.length; i++) {
if (i < odd) {
array1[i] = array3[i];
} else {
array1[i] = array2[(i + 1) - even];
}
}
System.out.println("\nAfter sorting:\n");
showAray(array1, array1.length);
}
}
I know there is a logical error here, but I can't figure out what exactly. Is there any way to change the logic to work with all integers? Thanks.
array1[i] = array2[(i + 1) - even];
EDIT - Here is the stacktrace.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at ary.main(arytest.java:67)
Java Result: 1
Change this
array1[i] = array2[(i + 1) - even];
to
array1[i] = array2[i - odd];
I guess this is what you want
i need a simple negative number counter in a basic bubble sort.. i have this code
public static void printArray(int[] a) {
System.out.print("Tvoj niz je: ");
for (int k = 0; k < a.length; ++k){
System.out.println();
System.out.println ( a[k] );
}
System.out.println();
}
public static void bubbleSort(int[] a) {
int neg;
int temp;
for (int i = 0; i < a.length; ++i) {
for (int j = 0; j < a.length - i - 1; ++j) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] a = {7, 4, 11, -3, 1, -2};
bubbleSort(a);
printArray(a);
now i need to have on output the number of negative numbers in array in this case number 2, because i have -3 and -2... :)
int negCount = 0;
for(int i = 0; i < a.length; i++) {
if(a[i] < 0) {
negCount++;
}
}
negCount will hold the negative integers count.
I am writing a JAVA code to generate all permutations of a integer array.
Though I am getting the number of permutations right, the permutations themselves are not correct.
On running I obtain:
Input array Length
3
1
2
3
0Permutation is
1, 2, 3,
##########################
1Permutation is
1, 3, 2,
##########################
2Permutation is
3, 1, 2,
##########################
3Permutation is
3, 2, 1,
##########################
4Permutation is
1, 2, 3,
##########################
5Permutation is
1, 3, 2,
##########################
6 number of permutations obtained
BUILD SUCCESSFUL (total time: 3 seconds)
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}
int temp=input[i];
input[i]=input[startindex];
input[startindex]=temp;
Permute(input, startindex+1);
You've swapped an element before calling Permute but you need to swap it back again afterwards to keep consistent positions of elements across iterations of the for-loop.
This is the best solution I have seen so far :
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6 };
permute(0, a);
}
public static void permute(int start, int[] input) {
if (start == input.length) {
//System.out.println(input);
for (int x : input) {
System.out.print(x);
}
System.out.println("");
return;
}
for (int i = start; i < input.length; i++) {
// swapping
int temp = input[i];
input[i] = input[start];
input[start] = temp;
// swap(input[i], input[start]);
permute(start + 1, input);
// swap(input[i],input[start]);
int temp2 = input[i];
input[i] = input[start];
input[start] = temp2;
}
}
check this out
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}
//This will give correct output
import java.util.Scanner;
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}
You can solve this using recursive calls.
https://github.com/Pratiyush/Master/blob/master/Algorithm%20Tutorial/src/arrays/Permutations.java
public void swap(int[] arr, int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public void permute(int[] arr, int i)
{
if (i == arr.length)
{
System.out.println(Arrays.toString(arr));
return;
}
for (int j = i; j < arr.length; j++)
{
swap(arr, i, j);
permute(arr, i + 1); // recurse call
swap(arr, i, j); // backtracking
}
}
public static void main(String[] args) {
Permutations permutations = new Permutations();
int[] arr = {1, 2, 3,4};
permutations.permute(arr, 0);
}
Also, other approaches are available in
http://www.programcreek.com/2013/02/leetcode-permutations-java/
http://www.programcreek.com/2013/02/leetcode-permutations-ii-java/
public class PermuteArray {
public static void permute(char[] input2, int startindex) {
if (input2.length == startindex) {
displayArray(input2);
} else {
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}
}
}
private static void displayArray(char[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + "; ");
}
System.out.println();
}
public static void main(String[] args) {
char[] input = { 'a', 'b', 'c', 'd'};
permute(input, 0);
}
}
import java.util.ArrayList;
public class RecursivePermGen {
void permGen(int n, int m, ArrayList<Integer> cur) {
if(m == 0) {
System.out.println(cur);
return;
}
for(int i = 1; i <= n; i++) {
cur.add(0, i);
permGen(n, m-1, cur);
cur.remove(0);
}
}
public static void main(String[] args) {
RecursivePermGen pg = new RecursivePermGen();
ArrayList<Integer> cur = new ArrayList<Integer>();
pg.permGen(2, 2, cur);
}
}
I have simple answer for this question, you can try with this.
public class PermutationOfString {
public static void main(String[] args) {
permutation("123");
}
private static void permutation(String string) {
printPermutation(string, "");
}
private static void printPermutation(String string, String permutation) {
if (string.length() == 0) {
System.out.println(permutation);
return;
}
for (int i = 0; i < string.length(); i++) {
char toAppendToPermutation = string.charAt(i);
String remaining = string.substring(0, i) + string.substring(i + 1);
printPermutation(remaining, permutation + toAppendToPermutation);
}
}
}
A solution i have used several times (mostly for testing purposes) is in the following gist. It is based on the well-known algorithm to generate permutations in lexicographic order (no recursion):
/**
* Compute next (in lexicographic order) permutation and advance to it.
*
* Find greater index i for which a j exists, such that:
* j > i and a[i] < a[j] (i.e. the 1st non-inversion).
* For those j satisfying the above, we pick the greatest.
* The next permutation is provided by swapping
* items at i,j and reversing the range a[i+1..n]
*/
void advanceToNext() {
// The array `current` is the permutation we start from
// Find i when 1st non-inversion happens
int i = n - 2;
while (i >= 0 && current[i] >= current[i + 1])
--i;
if (i < 0) {
// No next permutation exists (current is fully reversed)
current = null;
return;
}
// Find greater j for given i for 1st non-inversion
int j = n - 1;
while (current[j] <= current[i])
--j;
// Note: The range a[i+1..n] (after swap) is reverse sorted
swap(current, i, j); // swap current[i] <-> current[j]
reverse(current, i + 1, n); // reverse range [i+1..n]
}
A complete solution (in the form of a class) lies here:
https://gist.github.com/drmalex07/345339117fef6ca47ca97add4175011f