Week 1.md 1.8KB

Week 1

Problem 1

Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[].

Input : arr[] = {10, 20, 80, 30, 60, 50,
                     110, 100, 130, 170}
          x = 110;
Output : 6
Element x is present at index 6

Input : arr[] = {10, 20, 80, 30, 60, 50,
                     110, 100, 130, 170}
           x = 175;
Output : -1
Element x is not present in arr[].

Hint: linear search

/ Trinh's Solution I can use a for loop to search each index (i) of the array, using a variable to store the previous (or first index) to compare to... using if == ?, if true, return the index (i), if false, continue searching. /

Problem 2

Problem: Write a Java program to arrange the elements of an given array of integers where all negative integers appear before all the positive integers.

Input: { 2, 5, -55, 8, -72, -1, 53 }

Output: { -55, -72, -1, 2, 5, 8, 53 }

Trinh's Solution Nested for loop to bubble sort? We can start at index 0, and start comparing, with each pass of the array, it will slowly move the elements until it becomes sorted.

If we simply wanted the negative before the positive, we might not need a nested for loop? Since we aren't checking for < or > but rather just if it's positive or negative?

public static void sortLoop(int[] inputArray) { int tempVal = inputArray[0];

for (int i = 0; i < inputArray.length - 1; i++) {

the first for loop gets the first number and actively compares it to the next through the next for loop

using the tempVal variable we don't lose the value we replace and can then swap it to the right position.

/

for (int j = 0; j < inputArray.length - i; j++) {
    if (inputArray[j] > inputArray[i]) {
        tempVal = inputArray[j];
        inputArray[j] = inputArray[j+1];
        tempVal = inputArray[j+1];
    }
}

}

}