Whats wrong with my QuickSort implementation? - java

class PartitionIt
{
public static void partitionIt(int[] a, int l, int r, int pivot)
{
int i,j;
i = j = l+1;
while(j<= r)
{
if(a[j] <= a[pivot])
{
swap(a,j,i);
i++;
}
j++;
}
swap(a,pivot,--i);
}
public static void swap(int[] a, int j, int i)
{
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
public static void displayArray(int[] a)
{
for(int i:a)
System.out.print(i+" ");
System.out.println();
}
public static void QuickSort(int[] a, int l, int r)
{
if(r <= l)
return;
int pivot = getPivot(a,l,r);
partitionIt(a,l,r,pivot);
QuickSort(a,l,pivot);
QuickSort(a,pivot+1,r);
}
public static int getPivot(int[] a,int l,int r)
{
return l;
}
public static void main(String[] args)
{
int[] a = {3,2,8,5,1,4,7,6};
int[] b = {1,2,3,4,5,6,7,8,9,0};
int[] c = {5,4,2,4,7,6,5,3,2,1,10};
displayArray(a);
System.out.println("After Parititon with pivot 3");
QuickSort(a,0,a.length-1);
displayArray(a);
System.out.println();
displayArray(b);
System.out.println("After Parititon with pivot 1");
QuickSort(b,0,b.length-1);
displayArray(b);
System.out.println();
displayArray(c);
System.out.println("After Parititon with pivot 5");
QuickSort(c,0,c.length-1);
displayArray(c);
System.out.println();
}
}
3 2 8 5 1 4 7 6
After Parititon with pivot 3
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9 0
After Parititon with pivot 1
0 1 2 3 4 5 6 7 8 9
5 4 2 4 7 6 5 3 2 1 10
After Parititon with pivot 5
1 2 2 4 3 4 5 5 6 7 10
It is not sorting properly in last case.
Can anyone help here. I m stuck from so long.
Thanks in advance!

At This snippet:
if(a[j] <= a[pivot])
{
swap(a,j,i);
i++;
}
The '<=' should be '<'.
while the sequence was sorted to 1 2 2 4 3 4 5 5 7 6 10,the pivot is '4'(the left one),while compare 4 <= 4,i++, this cause the swap(a,pivot,--i) change the location of '4'(the right one ) to '4'(the left one),rather than change the '3' to '4'.

Related

Adding large matrices ArrayIndexOutOfBoundsException

I am writing a program which adds two integer matrices together and I am running into an ArayIndexOutOfBounds exception when trying to process larger matrices. Any advice on how to fix this issue would be greatly appreciated.
ArrayOutOfBoundsException on cmd prompt
Here is the class in which the error is occuring:
import java.util.ArrayList;
public class ThreadMaker
{
public static int count=0;
public static void addmatrix(int[][] mat_A,int[][] mat_B,int[][] submatrix1,int[][] submatrix2,int N,int M)throws Exception
{
ThreadOperation m1;
ThreadOperation.initialize(N,M);
ArrayList<Thread> threads = new ArrayList<Thread>();
int c=0,d;
while(c<N)
{
d=0;
while(d<M)
{
int i=0,j=0,k,l;
for(k=0,i=c; i < c + N/2; i++, k++)
{
for(l=0,j=d; j < d + M/2; j++, l++)
{
submatrix1[k][l]=mat_A[i][j];
submatrix2[k][l]=mat_B[i][j];
}
}
m1=new ThreadOperation(mat_A,mat_B,submatrix1,submatrix2,N,M,c,d);
Thread thread =new Thread(m1);
thread.start();
threads.add(thread);
thread.join();
d=d+M/2;
}
c=c+N/2;
}
}
public static void devidematrix(int[][] mat_A,int[][] submatrix,int N,int M)
{
int c=0,d;
while(c<N)
{
d=0;
while(d<M)
{
int i=0,j=0,k,l;
for( k=0,i=c;i<c+N/2;i++,k++)
{
for( l=0,j=d;j<d+M/2;j++,l++)
{
submatrix[k][l]=mat_A[i][j];
}
}
d=d+M/2;
}
c=c+N/2;
}
}
public synchronized static void printmatrix(int[][] matrix,int row,int col)
{
System.out.print(" ");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
System.out.print(matrix[i][j]+" ");
}
}
System.out.print(" ");
}
}
Here is the martix from the matrix2.txt file:
4 7
2 3 1 2 5 1 2
3 1 2 2 2 4 4
1 2 3 2 7 2 1
3 6 1 5 1 3 5
6 5 4 1 4 3 1
3 3 2 2 1 1 2
7 5 4 3 2 5 3
2 1 8 4 8 4 4
If any more information is need please let me know.

Find all combinations with repetitions but without duplicate rows

There is an array of 1, 2, 3, 4. It is necessary to make all possible combinations of 3 size series, the elements can be repeated. The order of the elements in the row is not important. For instance:
114 = 411 = 141.
I can't find a suitable algorithm. I have found this algorithm, but there can be no repetitions of elements, like 111 or 113, only 123,124 etc.
public void doit(){
String[] arr = {"1", "2", "3","4"};
int count = fuctorial(arr.length);
int max = arr.length - 1;
System.out.println("Вариантов " + count);
int shift = max;
String t;
while (count > 0) {
t = arr[shift];
arr[shift] = arr[shift - 1];
arr[shift - 1] = t;
print(arr);
count--;
if (shift < 2) {
shift = max;
} else {
shift--;
}
}
}
static void print(String[] arr) {
System.out.println(Arrays.toString(arr));
}
static int fuctorial(int n) {
return (n > 0) ? n * fuctorial(n - 1) : 1;
}
Try this.
static void combination(int[] a, int n) {
int size = a.length;
int[] selected = new int[n];
new Object() {
void print() {
for (int i = 0; i < n; ++i)
System.out.print(a[selected[i]] + " ");
System.out.println();
}
void combination(int index, int prev) {
if (index >= n)
print();
else
for (int i = prev; i < size; ++i)
combination(index + 1, selected[index] = i);
}
}.combination(0, 0);
}
and
int[] a = {6, 7, 8, 9};
combination(a, 3);
output:
6 6 6
6 6 7
6 6 8
6 6 9
6 7 7
6 7 8
6 7 9
6 8 8
6 8 9
6 9 9
7 7 7
7 7 8
7 7 9
7 8 8
7 8 9
7 9 9
8 8 8
8 8 9
8 9 9
9 9 9
public void func() {
boolean[] check = new boolean[49];
for(int i=1; i <=4; i++ ) {
for(int j=1; j <=4; j++) {
for(int k=1; k<=4; k++) {
int sum = i*i + j*j + k*k;
if(!check[sum]) {
check[sum] = true;
System.out.println(i + "," + j + "," + k);
}
}
}
}
}
idea is: we take a triplet, calculate the sum of squares, and check if we already had a triplet with that sum. identical triplets will have the same sum of squares.
the sum of squares will always be in the range 3-48. also, the sum is unique to each combination of numbers just like you require.
Complexity is O(N^3) where N is the size of the array. since we need combinations of 3 elements, i don't think you can go below that.
UPDATE: to make is more general, use a HashSet for the sums instead of the boolean array, and iterate 3 nested loops over the input array. calculate the sum of squares and check against the HashSet.
Performance Optimization: calculate the squares of each element in the array in advance so you dont have to calculate them over and over again.

Insertion Sort pt2 -Hackerrank

can someone please check my code as to why the last index is not working as intended? Any advice on how to improve this is much appreciated.
import java.io.*;
import java.util.*;
public class Solution {
public static void insertionSortPart2(int[] ar) {
int key;
int seen;
for (int i = 0 ; i < ar.length-1; i++){
key = ar[i];
seen = i;
while (seen <ar.length-1 && ar[seen+1]<key){
ar[seen]= ar[seen+1];
seen = seen+1;
}
ar[seen]=key;
printArray(ar);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int[] ar = new int[s];
for(int i=0;i<s;i++){
ar[i]=in.nextInt();
}
insertionSortPart2(ar);
}
private static void printArray(int[] ar) {
for(int n: ar){
System.out.print(n+" ");
}
System.out.println("");
}
}
Input (stdin) 6 1 4 3 5 6 2
Your Output (stdout) 1 4 3 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 3 4 5 2 6
Expected Output 1 4 3 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 2 3 4 5 6 Compiler Message Wrong Answer
You are doing it in wrong way. Read the part 1 again.
Assume that first element is sorted. Then try to insert element one by one in sorted list.
Try this:
public static void insertionSortPart2(int[] ar) {
int key;
int seen;
for (int i = 1 ; i < ar.length; i++){
key = ar[i];
seen = i;
while (seen > 0 && ar[seen-1] > key) {
ar[seen] = ar[seen-1];
seen = seen - 1;
}
ar[seen]=key;
printArray(ar);
}
}

Printing a number triangle

CS student here. I've just received an introduction to loops and I'm not sure I understand them very well. I'm trying to print a triangle of numbers n, such that if n = 4 you'd get something like this:
4
3 7
2 6 9
1 5 8 10
Instead I'm winding up with something like:
4
3 5
Suffice it to say I'm lost. Here's my code:
void drawT3 (int n)
{
int k = 1;
int t = 1;
for (int i=1;i<=n;i++)
{
k = n;
int j;
for (j=1;j<=n-i;j++)
System.out.print(" ");
for (j=1;j<=t;j++)
{
System.out.printf("%3d",k);
k += (n - j);
}
n--;
t++;
System.out.println();
}
}
void printTriangle(int n)
{
// build an auxiliary 2D array
final int t[][] = new int[n][n];
int i = 1;
for (int s = n - 1; s <= 2 * (n - 1); s++)
{
for (int x = s - n + 1; x < n; x++)
{
t[x][s - x] = i++;
}
}
// print the array
for (int y = 0; y < n; y++)
{
for (int x = 0; x < n; x++)
{
if (t[x][y] > 0)
{
System.out.printf("%3d", t[x][y]);
}
else
{
System.out.printf(" ");
}
}
System.out.println(); // start new line
}
}
Build an auxiliary 2D array of size n.
Put numbers into array as human will do, from 1 to n, following the diagonals. s in the code represents x + y sum. That sum is constant for every diagonal. In the first diagonal (the longest one) sum is equal to n - 1. In the second diagonal sum is 1 more, n. In the last "diagonal" (bottom right corner) the sum is 2 * (n - 1). That's exactly our loop: for (int s = n - 1; s <= 2 * (n - 1); s++). Having the sum and x we can obtain y with simple subtraction, y = s - x.
Print the array. Each cell of array is initialized with 0 (int's default value). So, if a cell has zero, we just print 3 spaces, to preserve the shape of triangle.
PS. My code was written for "educational purposes" :) To show how it can be done, in easy way. It's not optimized for speed nor memory.
public static void main(String[] args) {
// TODO code application logic here
triangle(4);
}
static public void triangle(int n){
int x = 0;
for (int i = n;i>0;i--){
System.out.print(i + " ");
x = i+n;
for (int j=0;j<n-i;j++){
System.out.print(x - j + " ");
x = x + n -j;
}
System.out.println("");
}
}
Output for 4:
4
3 7
2 6 9
1 5 8 10
Output for 6:
6
5 11
4 10 15
3 9 14 18
2 8 13 17 20
1 7 12 16 19 21
Observe that there are many ways to print out a triangle of numbers as described above, For example, here are two,
// for n=5,
// 1 2 3 4 5
// 6 7 8 9
// 10 11 12
// 13 14
// 15
And
// 5
// 4 9
// 3 8 12
// 2 7 11 14
// 1 6 10 13 15
And since recursion is Fun!
class triangle
{
//Use recursion,
static int rowUR( int count, int start, int depth )
{
int ndx;
if(count<=0) return start;
//-depth?
for (ndx=0;ndx<depth;ndx++)
{
System.out.print(" ");
}
//how many? 5-depth, 5,4,3,2,1
for( ndx=0; ndx<count; ++ndx )
{
System.out.printf("%3d",start+ndx);
}
System.out.printf("\n");
if( count>0 )
{
rowUR( count-1, ndx+start, depth+1 );
}
return ndx;
}
//Use recursion,
static int rowLR( int count, int start, int depth )
{
int ndx, accum;
if( start < count )
rowLR( count, start+1, depth+1 );
for( ndx=0; ndx<depth; ++ndx )
{
System.out.print(" ");
}
accum=start;
//how many? 5-depth, 1,2,3,4,5
for( ndx=0; ndx<(count-depth); ++ndx )
{
System.out.printf("%3d",accum);
accum+=count-ndx;
}
System.out.printf("\n");
return ndx;
}
public static void main(String[] args)
{
int count=4, depth=0, start=1;
System.out.printf("rowUR\n");
rowUR( count=5, start=1, depth=0 );
System.out.printf("rowLL\n");
rowLL( count=5, start=1, depth=0 );
}
};
int n=4,i,j,k,t;
for (i=n;i>=1;i--)
{
t=i;
k=n;
for(j=1;j<i;j++)
System.out.printf(" "); // for leading spaces
System.out.printf("%3d",i); // for first digit(or number) in each row (in your example these are 4,3,2,1)
for(j=i;j<n;j++)
{
t+=k;
System.out.printf("%3d",t);
k--;
}
System.out.print("\n");
}
OUTPUT:
for n=8
8
7 15
6 14 21
5 13 20 26
4 12 19 25 30
3 11 18 24 29 33
2 10 17 23 28 32 35
1 9 16 22 27 31 34 36
http://ideone.com/C1O1GS
make space around numbers according to your need.
PS: I would never suggest to write any pattern code using array unless it is very complicated. array will use extra memory space.

How to get the following formatted output?

I wrote the code to get the following formatted output, but when I enter number of rows in double digits, the output format changes. Why? How can I fix this?
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
Here is my code:
import java.util.*;
class PTri {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
int numrow = sc.nextInt();
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= numrow - i; j++) {
System.out.print(" ");
}
for (int k = 1; k < i * 2; k++) {
System.out.print(Math.min(k, i * 2 - k) + " ");
}
System.out.println();
}
}
}
It's because the value in double digit will change the whole architecture.The set will shift to right one place. So you can put a condition like this. I have added one extra space between numbers to improve visibility.
import java.util.*;
class PTri {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
int numrow = sc.nextInt();
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= (numrow - i); j++) {
System.out.print(" ");
}
for (int k = 1; k < i * 2; k++) {
int temp = Math.min(k, i * 2 - k);
if (temp > 9) {
System.out.print(temp + " ");
} else {
System.out.print(temp + " ");
}
}
System.out.println();
}
}
}
In this example I counted the digits, and for every digit I add an extra space.
The output of the value is formatted with leading zeros (digit-count).
public static void main(final String[] args) {
final Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
final int numrow = 100;// sc.nextInt();
final int digits = (int) Math.log10(numrow) + 1;
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= numrow - i; j++) {
System.out.print(" ");
for (int l = 0; l < digits; l++) {
System.out.print(" ");
}
}
for (int k = 1; k < i * 2; k++) {
final int value = Math.min(k, i * 2 - k);
System.out.print(String.format("%0" + digits + "d ", value));
}
System.out.println();
}
}
You can use String.format method:
"%2d" - format as a two-digit number.
"%02d" - format as a two-digit number with leading zeros.
Example:
// int n = 5;
int n = 12;
// number of digits
int digits = String.valueOf(n).length();
// format string
String format = "%" + digits + "d";
// output
System.out.println("n=" + n + ", format=" + format);
IntStream.rangeClosed(1, n)
.mapToObj(i -> IntStream.rangeClosed(-n, i)
.map(Math::abs)
.map(j -> j = i - j)
.filter(j -> j != 0)
.mapToObj(j -> j > 0 ?
String.format(format, j) : " " .repeat(digits))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
Output:
n=5, format=%1d
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
n=12, format=%2d
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 11 10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 11 12 11 10 9 8 7 6 5 4 3 2 1
See also: Print the sum of the row and column in a 2d array after each row

Categories

Resources