Upload
ramusgotmail
View
252
Download
0
Embed Size (px)
Citation preview
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 1/23
My Code Book Ramesh Perumalsamy
public static Object MYCodeBook;
A collection of the code and the experiments galore.
Also a supplement to the online content @
http://bestsourced.wordpress.com/
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 2/23
Merge Sort20 April 2011
Source code:
/**
* @author Ramesh
*/
public class MergeSort {
public static int ARRAYLEN = 10;
private static int MAX = 32768; // Sentinel
public static void main(String[] args) {
MergeSort mSort = new MergeSort();
// Creation and population of the Input array
Integer[] lstInt = new Integer[ARRAYLEN ];for (int i = 0; i < ARRAYLEN ; i++) {
lstInt[i] = ((int) (Math.random() * 100)); //Range : 0 - 99
}
System.out.print("Before : ");
mSort.printArray(lstInt);
mSort.mergeSort(lstInt, 0, ARRAYLEN - 1);
System.out.println("");
System.out.print("After : ");
mSort.printArray(lstInt);
}
// Merge Sort function - Recursive implementation
public void mergeSort(Integer[] lst, int p, int r) {
int q = 0;
if (p < r) {
q = (p + r) / 2;
mergeSort(lst, p, q);
mergeSort(lst, q + 1, r);
mergeProc(lst, p, q, r);
}
return;
}
// Merging Procedure - Merge into a single sorted array
public void mergeProc(Integer[] lst, int p, int q, int r) {
int n1, n2, i = 0, j = 0, k = 0;n1 = q - p + 1;
n2 = r - q;
Integer[] L = new Integer[n1 + 1]; // Left array
Integer[] R = new Integer[n2 + 1]; // Right array
for (i = 0; i < n1; i++) {
L[i] = lst[i + p];
}
for (j = 0; j < n2; j++) {
R[j] = lst[j + q + 1];
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 3/23
}
R[j] = MAX ; // Sentinel Values
L[i] = MAX ; // Sentinel Values
k = i = j = 0;
for (k = p; k <= r; k++) {
if (L[i] <= R[j]) { // Compare the first element of
lst[k] = L[i]; // Left and Right arrays
i++; // and populate the least value
} else { // Increment the appropriate pointer
lst[k] = R[j];
j++;
}
}
return;
}
public void mergeProcNoSentinel(Integer[] lst, int p, int q, int r) {
int n1, n2, i = 0, j = 0, k = 0;
n1 = q - p + 1;
n2 = r - q;
Integer[] L = new Integer[n1]; // Left array Integer[] R = new Integer[n2]; // Right array
for (i = 0; i < n1; i++) {
L[i] = lst[i + p];
}
for (j = 0; j < n2; j++) {
R[j] = lst[j + q + 1];
}
// R[j] = MAX; // NO Sentinel Values
// L[i] = MAX; // NO Sentinel Values
k = i = j = 0;
for (k = p; k <= r; k++) {
if (j >= n2 || ((i < n1) && (L[i] <= R[j]))) {
lst[k] = L[i];
i++;
} else {
lst[k] = R[j];
j++;
}
}
return;
}
// Array printing function - Generic
public <T> void printArray(T[] a) {
for (T t : a) {
System.out.print(t + " ");
}return;
}
}
Sample Output:Before : 32 19 80 17 64 17 38 84 69 49
After : 17 17 19 32 38 49 64 69 80 84
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 4/23
Insertion Sort & Binary Search21 April 2011
Source code:
/* @author rparumal
*
*/
public class InsertionSort {
/**
* @param args
*/
private static int ARRAYLEN = 10;
public static void main(String[] args) {
// TODO Auto-generated method stub
InsertionSort inSort = new InsertionSort();
Integer[] lstInt = new Integer[ARRAYLEN ];
for (int i = 0; i < ARRAYLEN ; i++) {
lstInt[i] = ((int) (Math.random() * 100));
}
System.out.print("Before : ");
inSort.printArray(lstInt);
inSort.insertSort(lstInt);
System.out.println("");
System.out.print("After : ");
inSort.printArray(lstInt);
System.out.println("");
int x = 0;
int find = inSort.BinarySearchRecursive(lstInt, 0, ARRAYLEN - 1,
lstInt[x = (int) (Math.random() * ARRAYLEN )]);
if (find >= 0) {
System.out.println("Found Recursive " + lstInt[x]
+ " @ location : " + (find + 1));
}
x = 0;
find = inSort.BinarySearchIterative(lstInt, 0, ARRAYLEN - 1,
lstInt[x = (int) (Math.random() * ARRAYLEN )]);
if (find >= 0) {
System.out.println("Found Iterative " + lstInt[x]+ " @ location : " + (find + 1));
}
System.out.println();
}
public void unnamedSort(Integer[] lst) {
int temp = 0;
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 5/23
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 6/23
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 7/23
Sum of X Numbers in an Array21 April 2011
Problem : Find if in a sorted array the sum of any 2 (or 3) of the elements equals a given sum.
Source Code:
import java.util.Arrays;
public class SumOfNosInArray {
/**
* @param args
*/
public static int ARRAYLEN = 10;
public static int low = 0; public static int high = 0;
public static int start = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
SumOfNosInArray sna = new SumOfNosInArray();
int[] arr = new int[ARRAYLEN ];
for (int i = 0; i < ARRAYLEN ; i++) {
arr[i] = ((int) (Math.random() * 10)); // Range : 0 - 99
}
System.out.println("Initial :");
sna.printArrayInt(arr);Arrays.sort(arr);
System.out.println("Sorted :");
sna.printArrayInt(arr);
System.out.println("Sum of Two numbers Sequence...");
int sum = (int) (Math.random() * 19);
low = 0;
high = arr.length - 1;
if (sna.SumOfTwoNos(arr, sum)) {
System.out.println("Sum of " + arr[low ] + " and " +
arr[high]
+ " is " + sum);
} else {System.out.println("Sum " + sum + " not found");
}
System.out.println("Sum of Three numbers Sequence...");
sum = (int) (Math.random() * 28);
low = 0;
high = arr.length - 1;
if (sna.SumOfThreeNos(arr, sum)) {
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 8/23
System.out.println("Sum of " + arr[start] + " and " +
arr[low ]
+ " and " + arr[high] + " is " + sum);
} else {
System.out.println("Sum " + sum + " not found");
}
}
public boolean SumOfTwoNos(int[] arr, int sum) {
int temp = 0;
while (low < high) {
System.out.println("Comparing " + arr[low ] + " and " +
arr[high]
+ " low = " + low + " high = " + high);
temp = arr[low ] + arr[high];
if (temp == sum) {
return true;
} else if (temp < sum) {
low ++;
} else {
high--;}
}
return false;
}
public boolean SumOfThreeNos(int[] arr, int sum) {
int temp = 0;
while (start < arr.length) {
System.out.println("For start = " + start + "...");
low = start + 1;
high = arr.length - 1;
temp = sum - arr[start];
if (SumOfTwoNos(arr, temp)) {
return true;
}
start++;
}
return false;
}
public void printArrayInt(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
}
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 9/23
Sample Output:
Initial :
9 3 9 6 7 1 6 5 7 8
Sorted :
1 3 5 6 6 7 7 8 9 9
Sum of Two numbers Sequence...Comparing 1 and 9 low = 0 high = 9
Comparing 1 and 9 low = 0 high = 8
Comparing 1 and 8 low = 0 high = 7
Comparing 1 and 7 low = 0 high = 6
Comparing 1 and 7 low = 0 high = 5
Comparing 1 and 6 low = 0 high = 4
Comparing 1 and 6 low = 0 high = 3
Comparing 1 and 5 low = 0 high = 2
Comparing 1 and 3 low = 0 high = 1
Sum 2 not found
Sum of Three numbers Sequence...
For start = 0...
Comparing 3 and 9 low = 1 high = 9Comparing 5 and 9 low = 2 high = 9
Comparing 5 and 9 low = 2 high = 8
Comparing 5 and 8 low = 2 high = 7
Sum of 1 and 5 and 8 is 14
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 10/23
Bubble Sort22 April 2011
Source Code:
/**
* @author rparumal
*
*/
public class BubbleSort {
public static int ARRAYLEN = 10;
public static void main(String[] args) {
BubbleSort bSort = new BubbleSort();
// Creation and population of the Input array
Integer[] lstInt = new Integer[ARRAYLEN ];
// Code for generating random input
/* * for (int i = 0; i < ARRAYLEN; i++) { lstInt[i] = ((int)
* (Math.random() * 100)); // Range : 0 - 99 }
*/
lstInt = new Integer[] { 10, 2, 3, 4, 5, 6, 7, 8, 9, 1 };
System.out.print("Before : ");
bSort.printArray(lstInt);
System.out.println("");
bSort.bubbleSortFunction(lstInt);
System.out.println("");
System.out.print("After : ");
bSort.printArray(lstInt);
}
// Bubble Sort function
public void bubbleSortFunction(Integer[] arr) {
boolean swap = true;
int i = 0, j = 0, temp;
while (swap) {
swap = false;
j++;
for (i = 0; i < ARRAYLEN - j; i++) {
if (arr[i] > arr[i + 1]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swap = true;}
}
System.out.print("Interation " + j + " : ");
this.printArray(arr);
System.out.println("");
}
return;
}
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 11/23
// Array printing function - Generic
public <T> void printArray(T[] a) {
for (T t : a) {
System.out.print(t + " ");
}
return;
}
}
Sample Output:
Before : 10 2 3 4 5 6 7 8 9 1
Interation 1 : 2 3 4 5 6 7 8 9 1 10
Interation 2 : 2 3 4 5 6 7 8 1 9 10
Interation 3 : 2 3 4 5 6 7 1 8 9 10
Interation 4 : 2 3 4 5 6 1 7 8 9 10Interation 5 : 2 3 4 5 1 6 7 8 9 10
Interation 6 : 2 3 4 1 5 6 7 8 9 10
Interation 7 : 2 3 1 4 5 6 7 8 9 10
Interation 8 : 2 1 3 4 5 6 7 8 9 10
Interation 9 : 1 2 3 4 5 6 7 8 9 10
Interation 10 : 1 2 3 4 5 6 7 8 9 10
After : 1 2 3 4 5 6 7 8 9 10
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 12/23
Lowest Index of Number23 April 2011
Problem:
Given a sorted array which contains repetitive elements, given a number return the lowest index of thenumber.
Source Code:import java.util.Arrays;
public class LowestIndexOfNumber {
/**
* Problem: Given a sorted array which contains repetitive elements,
given a
* number return the lowest index of the number.
*/
public static int ARRAYLEN = 10;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[ARRAYLEN ];
int search = 0;
System.out.print("Indices : 0 1 2 3 4 5 6 7 8 9");
System.out.println();
System.out.print("Initial array : ");
for (int i = 0; i < ARRAYLEN ; i++) {
arr[i] = (int) (Math.random() * 10);
System.out.print(arr[i] + " ");
}
search = (int) (Math.random() * 10);Arrays.sort(arr);
System.out.println();
System.out.print("Sorted array : ");
for (int i = 0; i < ARRAYLEN ; i++) {
System.out.print(arr[i] + " ");
}
int low = binSearch(arr, search, 0, ARRAYLEN - 1);
while (low > 0 && (arr[low - 1] == arr[low])) {
low--;
}
System.out.println();
System.out.println("Lowest index of " + search + " = " + low);
}
public static int binSearch(int[] arr, int key, int left, int right) {
if (left <= right) {
int middle = (left + right) / 2;
if (arr[middle] == key) {
return middle;
} else if (arr[middle] < key) {
return binSearch(arr, key, middle + 1, right);
} else {
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 13/23
return binSearch(arr, key, left, middle - 1);
}
}
return -1;
}
}
Sample Output:
Indices : 0 1 2 3 4 5 6 7 8 9
Initial array : 3 5 4 9 1 6 5 2 3 3
Sorted array : 1 2 3 3 3 4 5 5 6 9
Lowest index of 3 = 2
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 14/23
Unique Chars in a String23 April 2011
Problem:
Implement an algorithm to determine if a string has all unique characters.What if you can not useadditional data structures?
Source Code: public class UnquieCharsInString {
public static void main(String[] args) {
// TODO Auto-generated method stub
if (isAllCharsUnique("zadhzk")) {
System.out.println("Some chars are NOT unique");
} else {
System.out.println("All chars are unique");}
}
public static boolean isAllCharsUnique(String str) {
int chk = 0, val;
for (int i = 0; i < str.length(); i++) {
val = str.charAt(i) - 'a';
System.out.println("CharAt[" + i + "] - a = " + val);
if ((chk & (1 << val)) > 0) {
System.out.println("Value = " + (chk & (1 << val)));
return true;
} else {
chk |= (1 << val);}
System.out.println("Chk = " + chk);
}
return false;
}
}
Sample Output:CharAt[0] - a = 25
Chk = 33554432
CharAt[1] - a = 0
Chk = 33554433CharAt[2] - a = 3
Chk = 33554441
CharAt[3] - a = 7
Chk = 33554569
CharAt[4] - a = 25
Value = 33554432
Some chars are NOT unique
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 15/23
Reverse C-Style String23 April 2011
Problem:
Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters,including the null character.)
Source Code:
#include <stdio.h>
#include <conio.h>
void reverse(char *);
int main()
{
char str[20]; printf("Enter the string to be reversed : ");
gets(str);
reverse(str);
}
void reverse(char *str)
{
char *beg = str;
char *end = str;
char tmp;
if(str)
{
while(*end){
++end;
}
--end;
while(str<end)
{
tmp = *str;
*str++ = *end;
*end-- = tmp;
}
}
printf("Reversed string : %s", beg);
getch();
}
Sample Output:
Enter the string to be reversed : This Is A String
Reversed string : gnirtS A sI sihT
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 16/23
Stack Implementation (Array)25 April 2011
Implementation of a stack which takes Positive integer input using arrays.
Source Code:
public class StackImplementation {
static int STACKLEN = 10;
static int TOP = -1;
int[] stackArray;
final static private int PUSHCONST = 1;
final static private int POPCONST = 2;
final static private int PRINTCONST = 3;
final static private int EXITCONST = 4;
public static void main(String[] args) {
int c;
StackImplementation stack = new StackImplementation();
stack.stackArray = new int[STACKLEN ];
while (true) {
c = InputClass
.getInputIntScanner ("Enter the input choice\n(1
- Push 2 - Pop 3 - Print 4 - Exit) : ");
if (c <= 0) {
continue;
}
switch (c) {
case PUSHCONST :
c = InputClass.getInputIntScanner ("Enter the INT to
push : ");if (c <= 0) {
continue;
}
stack.push(c);
break;
case POPCONST :
System.out.println("Popped element = " +
stack.pop());
break;
case PRINTCONST :
stack.printStack();
break;
case EXITCONST :
System.out.println("Exiting Stack
Implementation...");
return;
}
}
}
public void push(int x) {
if (isStackFull()) {
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 17/23
System.out.println("The stack is Full");
return;
}
TOP ++;
stackArray[TOP ] = x;
}
public int pop() {
if (isStackEmpty()) {
System.out.println("The stack is Empty");
return -1;
}
return stackArray[TOP --];
}
public void printStack() {
if (isStackEmpty()) {
System.out.println("The stack is empty");
return;
}
System.out.print("Top ");for (int i = TOP ; i >= 0; i--) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
}
public boolean isStackEmpty() {
if (TOP < 0) {
return true;
} else {
return false;
}
}
public boolean isStackFull() {
if (TOP >= (STACKLEN - 1)) {
return true;
} else {
return false;
}
}
}
Sample Output:
Enter the input choice(1 - Push 2 - Pop 3 - Print 4 - Exit) :
1
Enter the INT to push :
34
Enter the input choice
(1 - Push 2 - Pop 3 - Print 4 - Exit) :
1
Enter the INT to push :
45
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 18/23
Enter the input choice
(1 - Push 2 - Pop 3 - Print 4 - Exit) :
3
Top 45 34
Enter the input choice
(1 - Push 2 - Pop 3 - Print 4 - Exit) :
1
Enter the INT to push :
89
Enter the input choice
(1 - Push 2 - Pop 3 - Print 4 - Exit) :
1
Enter the INT to push :
56
Enter the input choice
(1 - Push 2 - Pop 3 - Print 4 - Exit) :
3
Top 56 89 45 34
Enter the input choice
(1 - Push 2 - Pop 3 - Print 4 - Exit) :
2 Popped element = 56
Enter the input choice
(1 - Push 2 - Pop 3 - Print 4 - Exit) :
2
Popped element = 89
Enter the input choice
(1 - Push 2 - Pop 3 - Print 4 - Exit) :
3
Top 45 34
Enter the input choice
(1 - Push 2 - Pop 3 - Print 4 - Exit) :
4
Exiting Stack Implementation...
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 19/23
Queue Implementation (Array)25 April 2011
Implementation of a queue which takes Positive integer input using arrays.
Source Code:
public class QueueImplementation {
static int QUEUELEN = 10;
static int HEAD = 0;
static int TAIL = -1;
int[] queueArray;
final static private int ENQUEUECONST = 1;
final static private int DEQUEUECONST = 2;
final static private int PRINTCONST = 3;
final static private int EXITCONST = 4;
public static void main(String[] args) {
int c;
QueueImplementation queue = new QueueImplementation();
queue.queueArray = new int[QUEUELEN ];
while (true) {
c = InputClass
.getInputIntScanner ("Enter the input choice\n(1
- Enqueue 2 - Dequeue 3 - Print 4 - Exit) : ");
if (c <= 0) {
continue;
}
switch (c) {
case ENQUEUECONST :
c = InputClass.getInputIntScanner ("Enter the INT to
push : ");
if (c <= 0) {
continue;
}
queue.enqueue(c);
break;
case DEQUEUECONST :
System.out.println("Popped element = " +
queue.dequeue());
break;
case PRINTCONST :
queue.printQueue();
break;case EXITCONST :
System.out.println("Exiting Queue
Implementation...");
return;
}
}
}
public void enqueue(int x) {
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 20/23
if (isQueueFull()) {
System.out.println("The queue is full...");
return;
}
if (TAIL == (QUEUELEN - 1)) {
TAIL = 0;
} else {
TAIL++;
}
queueArray[TAIL] = x;
}
public int dequeue() {
if (isQueueEmpty()) {
System.out.println("The queue is empty...");
return -1;
}
int tmp = queueArray[HEAD ];
if (HEAD == (QUEUELEN - 1)) {
HEAD = 0;
} else {HEAD ++;
}
return tmp;
}
public void printQueue() {
int tmpTail;
if (isQueueEmpty()) {
System.out.println("The Queue is empty");
return;
}
if (TAIL < HEAD ) {
tmpTail = TAIL + QUEUELEN ;
} else {
tmpTail = TAIL;
}
System.out.print("HEAD : ");
for (int i = HEAD ; i <= tmpTail; i++) {
System.out.print(queueArray[i % QUEUELEN ] + " ");
}
System.out.print(" : TAIL ");
System.out.println();
}
public boolean isQueueEmpty() {
if (TAIL == -1 || HEAD == -1) {return true;
} else if (HEAD == TAIL) {
return true;
} else {
return false;
}
}
public boolean isQueueFull() {
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 21/23
if (TAIL == -1 || HEAD == -1) {
return false;
} else if (TAIL == (QUEUELEN - 1) && HEAD == 0) {
return true;
} else if (HEAD == (TAIL + 1)) {
return true;
} else {
return false;
}
}
}
Sample Output:
Enter the input choice
(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
3
The Queue is empty
Enter the input choice(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
`
Input integers only...
Enter the input choice
(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
1
Enter the INT to push :
12
Enter the input choice
(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
1
Enter the INT to push :
3 Enter the input choice
(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
1
Enter the INT to push :
4
Enter the input choice
(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
1
Enter the INT to push :
5
Enter the input choice
(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
1
Enter the INT to push :6
Enter the input choice
(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
3
HEAD : 12 3 4 5 6 : TAIL
Enter the input choice
(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
1
Enter the INT to push :
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 22/23
8/7/2019 My Code Book
http://slidepdf.com/reader/full/my-code-book 23/23
Popped element = 3
Enter the input choice
(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
2
Popped element = 4
Enter the input choice
(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
2
Popped element = 5
Enter the input choice
(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
3
HEAD : 6 7 8 9 10 11 50 : TAIL
Enter the input choice
(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
3
HEAD : 6 7 8 9 10 11 50 : TAIL
Enter the input choice
(1 - Enqueue 2 - Dequeue 3 - Print 4 - Exit) :
4
Exiting Stack Implementation...