Bubble sort in a Vector in Java - java

I'm creating a program that can sort objects (vector) with the Bubble sort method. I found a code on the internet which helped me alot to create it (Bubble sort in Arrays):
http://www.programmingsimplified.com/java/source-code/java-program-to-bubble-sort
When i compile the program i don't get any syntax error, but the results are not correct. I think i made an error in the IF-Statement, but i'm not sure if that's the only error. Here is the result i get when i run it:
Input number of integers to sort
5
Enter 5 integers
2
0
1
6
4
Sorted list of numbers
1
2
3
3
3
And here's my code:
import java.util.Scanner;
import java.util.*;
import java.io.*;
class BubbleSortVector {
public static void main(String []args) {
int n, c, d, swap;
Scanner in = new Scanner(System.in);
System.out.println("Input number of integers to sort");
n = in.nextInt();
Vector v ;
v = new Vector();
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
//v.addElement(c);
v.insertElementAt(in.nextInt(),c);
for (c = 0; c < ( n - 1 ); c++) {
for (d = 0; d < n - c - 1; d++) {
if ((Integer)v.elementAt(d) > (Integer)v.elementAt(d+1)) /* For descending order use < */
{
swap = (Integer)v.elementAt(d);
v.insertElementAt(d+1,d);
v.insertElementAt(swap,d+1);
}
}
}
System.out.println("Sorted list of numbers");
for (c = 0; c < n; c++)
System.out.println(v.elementAt(c));
}
}

// ...
Vector<Integer> v = new Vector<>();
// ...
for (c = 0; c < (n - 1); c++) {
for (d = 0; d < n - c - 1; d++) {
if (v.get(d) > v.get(d + 1)) {
swap = v.get(d);
v.set(d, v.get(d + 1));
v.set(d + 1, swap);
}
}
}
// ...

Your following code is wrong, inserting d+1 at index d means you're using the value of the loop index/counter into the vector, not the actual value that is at d+1
swap = (Integer)v.elementAt(d);
v.insertElementAt(d+1,d); // this is incorrect, d is the index/loop counter
v.insertElementAt(swap,d+1);
Chage that middle line to:
v.insertElement((Integer)v.elementAt(d+1), d);

you can solve it by simple swapping method. after loop you print the array.
int[] Array = new int[5]{2 , 0 , 6 , 1 , 4};
int temp = 0;
for (int i = 0; i < Array.Length; i++)
{
for (int j = 0; j < Array.Length - 1; j++)
{
if (Array[j] > Array[j + 1])
{
temp = Array[j + 1];
Array[j + 1] = Array[j];
Array[j] = temp;
}
}
}

Related

Java How do i repeat sort until no swaps are done in bubblesort?

I am taking 10 elements and performing a bubble sort on them. I want to add an algorithm that repeats the sort until no swaps are needed to make this more efficient.
Essentially I want to:
repeat until no swaps done in a pass
For elements 1 to (n-1)
compare contents of element value 1 with the contents of the next value
if value 1 is greater than value 2
then swap the values
This is what I have done so far :
{
//create array
int[] iList = new int[10];
Scanner sc = new Scanner(System.in);
//takes in array input for 10 numbers
System.out.println("Enter a array of numbers ");
for(int i = 0; i< 10; i++ )
{
int num = i + 1;
System.out.println("Enter number " + num);
iList[i] = sc.nextInt();
}
//Bubble sorts the array
System.out.println("The array =");
for(int a = 0; a < iList.length; a++ )
{
for(int b = a+1; b < iList.length; b++)
{
if(iList[a] > iList[b])
{
int iTemp = iList[a];
iList[a] = iList[b];
iList[b] = iTemp;
}
System.out.println("Progress = " + Arrays.toString(iList) );
}
}
} ```
Here is my implementation :
public static void sort(int[] nums) {
boolean isSwapped;
int size = nums.length - 1;
for (int i = 0; i < size; i++) {
isSwapped = false;
for (int j = 0; j < size - i; j++) {
if (nums[j] > nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
isSwapped = true;
}
}
if (!isSwapped) break;
}
System.out.println("Sorted Array: " + Arrays.toString(nums));
}

How to check each variable in the array, if the next element in the array is increasing?

I'm supposed to write a program that reads an array of ints and outputs the number of "triples" in the array.
A "triple" is three consecutive ints in increasing order differing by 1 (i.e. 3,4,5 is a triple, but 5,4,3 and 2,4,6 are not).
How do I check for the "triples"?
Current Code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] array = new int[size];
int iterator = 0;
for(int i = 0; i < size; i++){
array[i] = scanner.nextInt();
} for(int j =0; j < size; j++){
iterator++;
}
}
}
The following code loops through the entire array of integers. Inside of the loop it is checked if the third integer exists inside of the array ((i + 2) < array.Length) and the other 2 conditions are all about whether value1 is the same as the value2 decreased by 1 (array[i] == array[i + 1] - 1 and array[i + 1] == array[i + 2] - 1):
for (int i = 0; i < array.Length; i++)
{
if((i + 2) < array.Length && array[i] == array[i + 1] - 1 && array[i + 1] == array[i + 2] - 1)
System.out.println("Three values at indexes" + i + " " + (i + 1) + " and " + (i + 2) + " are a triple");
}
The code below is C# and sadly not compatible to Java that easily, I'll just leave that here for anyone who wants to know how its handled in C# (the vt variable is a so called ValueTriple):
(int, int, int) vt;
for (var i = 0; i < array.Length; i++)
{
if (i + 2 >= array.Length) continue;
vt = (array[i], array[i + 1], array[i + 2]);
if (vt.Item1 == vt.Item2 - 1 && vt.Item2 == vt.Item3 - 1)
Console.WriteLine($"Three values at indexes {i}, {i + 1} and {i + 2} (Values: {array[i]}, {array[i + 1]}, {array[i + 2]}) are a triple");
}
You may try following code
import java.util.Scanner;
public class Triplet {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] array = new int[size];
for(int i = 0; i < size; i++){
array[i] = scanner.nextInt();
}
Integer counter = 0;
for(int i = 0; i < size-2; i++) {
if(array[i] == array[i+1] - 1 && array[i] == array[i+2] - 2) { //checking if three consecutive ints in increasing order differing by 1
counter++;
}
}
System.out.println(counter);
}
}
Hope this will help.
A method to find out the number of triplets could look like this. You then just have to call the method depending how your input is obtained and you wish to present the result.
public static int getNumberOfTriplets(int[] toBeChecked) {
int numberOfTriplets = 0;
int nextIndex = 0;
while (nextIndex < toBeChecked.length - 2) {
int first = toBeChecked[nextIndex];
int second = toBeChecked[nextIndex + 1];
int third = toBeChecked[nextIndex + 2];
if ((first + 1 == second) && (second + 1 == third)) {
numberOfTriplets++;
}
nextIndex++;
}
return numberOfTriplets;
}
Regardless of allowing the numbers to be in more than one triplet, the answer is fairly similar in how I would personally approach it:
//determines if the input sequence is consecutive
public boolean isConsecutive(int... values) {
return IntStream.range(1, values.length)
.allMatch(i -> values[i] == values[i - 1] + 1);
}
public int countTriples(int[] input, boolean uniques) {
if (input.length < 3) {
return 0;
}
int back = 0;
for(int i = 2; i < input.length; i++) {
if (isConsecutive(input[i - 2], input[i - 1], input [i]) {
back++;
if (uniques) { //whether to disallow overlapping numbers
i += 2; //triple found, ignore the used numbers if needed
}
}
}
return back;
}
Then in calling it:
Int[] input = new int[] {1, 2, 3, 5, 6, 7, 8};
countTriples(input, true); //3
countTriples(input, false); //2

How do I calculate the number of Lines produced for the largest test-case when k = 12?

Problem: Given 6 < k < 13 integers, enumerate all possible subsets of size 6 of these integers in a sorted order. Since the size of the required subset is always 6 and the output has to be sorted lexicographically (the input is already sorted), the easiest solution is to use 6 nested loops as shown below.
I read that this code is efficient because it'll only produces 924 lines of output for the largest test-case when k = 12; however, I don't seem to get how the 924 lines were counted.
(Code solved using Iterative Complete Search problem solving paradigm)
public class loops {
public static void main(String[] args) {
int k = 12;
int[] S = {1,2,3,4,5,6,7,8,9,10,11,12};
for (int i = 0; i < k; i++) {
for (int a = 0; a < k - 5; a++) {
for (int b = a + 1; b < k - 4; b++) {
for (int c = b + 1; c < k - 3; c++) {
for (int d = c + 1; d < k - 2; d++) {
for (int e = d + 1; e < k - 1; e++) {
for (int f = e + 1; f < k; f++) {
System.out.println( S[a] + ""+ S[b] + S[c] + S[d] + S[e] + S[f]);
}
}
}
}
}
}
}
}
}
You're answering the combinatorial question how much "12 choose 6" is. By definition, the following holds:
12 choose 6 = 12!/6!(12-6)!
= 12!/(6!6!)
= 12*11*10...*2*1/(6*5*4*3*2*1*6*5*4*3*2*1)
= 479001600/(720*720)
= 924

Finding the count of common array sequencce

I am trying to the length of the longest sequence of numbers shared by two arrays. Given the following two arrays:
int [] a = {1, 2, 3, 4, 6, 8,};
int [] b = {2, 1, 2, 3, 5, 6,};
The result should be 3 as the the longest common sequence between the two is{1, 2, 3}.
The numbers must be in a sequence for the program to consider to count it.
I have thought about it and wrote a small beginning however, I am not sure how to approach this
public static int longestSharedSequence(int[] arr, int[] arr2){
int start = 0;
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < arr2.length; j++){
int n = 0;
while(arr[i + n] == arr2[j + n]){
n++;
if(((i + n) >= arr.length) || ((j + n) >= arr2.length)){
break;
}
}
}
That is a very good start that you have. All you need to do is have some way of keeping track of the best n value that you have encountered. So at the start of the method, declare int maxN = 0. Then, after the while loop within the two for loops, check if n (the current matching sequence length) is greater than maxN (the longest matching sequence length encountered so far). If so, update maxN to the value of n.
Since you also want the matching elements to be in sequential order, you will need to check that the elements in the two arrays not only match, but that they are also 1 greater than the previous element in each array.
Putting these together gives the following code:
public static int longestSharedSequence(int[] arr, int[] arr2) {
int maxN = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr2.length; j++) {
int n = 0;
// Check that elements match and that they are either the
// first element in the sequence that is currently being
// compared or that they are 1 greater than the previous
// element
while (arr[i + n] == arr2[j + n]
&& (n == 0 || arr[i + n] == arr[i + n - 1] + 1)) {
n++;
if (i + n >= arr.length || j + n >= arr2.length) {
break;
}
}
// If we found a longer sequence than the previous longest,
// update maxN
if (n > maxN) {
maxN = n;
}
}
}
return maxN;
}
I didn't think of anything smarter than the path you were already on:
import java.util.Arrays;
import java.util.Random;
public class MaxSeq {
public static void main(String... args) {
int[] a = new int[10000];
int[] b = new int[10000];
final Random r = new Random();
Arrays.parallelSetAll(a, i -> r.nextInt(100));
Arrays.parallelSetAll(b, i -> r.nextInt(100));
System.out.println(longestSharedSequence(a, b));
}
private static int longestSharedSequence(final int[] arr, final int[] arr2) {
int max = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr2.length; j++) {
int n = 0;
while ((i + n) < arr.length
&& (j + n) < arr2.length
&& arr[i + n] == arr2[j + n]) {
n++;
}
max = Math.max(max, n);
}
}
return max;
}
}
see: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem

Java permutations 2

I asked a question on helping me with this question about a week ago
Java permutations
, with a problem in the print permutation method. I have tidied up my code and have a working example that now works although if 5 is in the 5th position in the array it doesn't print it. Any help would be really appreciated.
package permutation;
public class Permutation {
static int DEFAULT = 100;
public static void main(String[] args) {
int n = DEFAULT;
if (args.length > 0)
n = Integer.parseInt(args[0]);
int[] OA = new int[n];
for (int i = 0; i < n; i++)
OA[i] = i + 1;
System.out.println("The original array is:");
for (int i = 0; i < OA.length; i++)
System.out.print(OA[i] + " ");
System.out.println();
System.out.println("A permutation of the original array is:");
OA = generateRandomPermutation(n);
printArray(OA);
printPermutation(OA);
}
static int[] generateRandomPermutation(int n)// (a)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
int swap = A[r];
A[r] = A[i];
A[i] = swap;
}
return A;
}
static void printArray(int A[]) {
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + " ");
System.out.println();
}
static void printPermutation(int[] p)
{
int n = p.length-1;
int j = 0;
int m;
int f = 0;
System.out.print("(");
while (f < n) {
m = p[j];
if (m == 0) {
do
f++;
while (p[f] == 0 && f < n);
j = f;
if (f != n)
System.out.print(")(");
}
else {
System.out.print(" " + m);
p[j] = 0;
j = m - 1;
}
}
System.out.print(" )");
}
}
I'm not too crazy about
int n = p.length-1;
followed by
while (f < n) {
So if p is 5 units long, and f starts at 0, then the loop will be from 0 to 3. That would seem to exclude the last element in the array.
You can use the shuffle method of the Collections class
Integer[] arr = new Integer[] { 1, 2, 3, 4, 5 };
List<Integer> arrList = Arrays.asList(arr);
Collections.shuffle(arrList);
System.out.println(arrList);
I don't think swapping each element with a random other element will give a uniform distribution of permutations. Better to select uniformly from the remaining values:
Random rand = new Random();
ArrayList<Integer> remainingValues = new ArrayList<Integer>(n);
for(int i = 0; i < n; i++)
remainingValues.add(i);
for(int i = 0; i < n; i++) {
int next = rand.nextInt(remainingValues.size());
result[i] = remainingValues.remove(next);
}
Note that if order of running-time is a concern, using an ArrayList in this capacity is n-squared time. There are data-structures which could handle this task in n log n time but they are very non-trivial.
This does not answer the problem you have identified.
Rather i think it identifies a mistake with your generateRandomPermutation(int n) proc.
If you add a print out of the random numbers generated (as i did below) and run the proc a few times it allows us to check if all the elements in the ARRAY TO BE permed are being randomly selected.
static int[] generateRandomPermutation(int n)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
System.out.println("random nums generated are: ");
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
System.out.print(r + " ");
Run the proc several times.
Do you see what i see?
Jerry.

Categories

Resources