Intermediate Programming PDF
Document Details
Uploaded by RichMoldavite2276
Tags
Summary
This document covers intermediate programming concepts, focusing on arrays, various searching and sorting algorithms. It details operations and provides examples related to arrays, including linear and binary searches, and covers methods for sorting arrays.
Full Transcript
Week 2-3 Intermediate Finding the Largest Element: Programming int max = arrayName; for (int num : arrayName) { Ar...
Week 2-3 Intermediate Finding the Largest Element: Programming int max = arrayName; for (int num : arrayName) { Arrays if (num > max) { Overview: max = num; An array is a fixed-size sequential } collection of elements of the same type. } Declaration Syntax: Passing Arrays to Methods: int[] arrayName; Arrays are passed by reference. void printArray(int[] array) { Combined Declaration and Initialization: for (int num : array) { int[] arrayName = new int[size]; System.out.print(num + " "); } Key Notes: } An array variable holds a reference to the array. Returning Arrays from Methods: Array size is fixed upon creation. Methods can return arrays. Indices are zero-based, ranging int[] reverseArray(int[] array) { from 0 to arrayName.length - 1. int[] reversed = new int[array.length]; for (int i = 0; i < array.length; i++) { Common Operations: reversed[i] = array[array.length - 1 - Initialization with Input Values: i]; for (int i = 0; i < arrayName.length; i++) { } arrayName[i] = scanner.nextInt(); return reversed; } } Initialization with Random Values: Searching in Arrays for (int i = 0; i < arrayName.length; i++) { Linear Search: arrayName[i] = (int) (Math.random() * Sequentially checks each element. 100); } Example: int linearSearch(int[] array, int key) { Displaying Elements: for (int i = 0; i < array.length; i++) { for (int i = 0; i < arrayName.length; i++) { if (array[i] == key) { System.out.println(arrayName[i]); return i; } } } Summing Elements: return -1; int total = 0; } for (int num : arrayName) { total += num; Binary Search: } Efficient search for sorted arrays. Algorithm: Insertion Sort: 1. Compare the key with the middle Builds a sorted list by inserting elements element. one by one. 2. Narrow the search to the left or right half based on comparison. void insertionSort(int[] array) { 3. Repeat until found or the range is for (int i = 1; i < array.length; i++) { empty. int current = array[i]; int j = i - 1; Example: while (j >= 0 && array[j] > current) { int binarySearch(int[] array, int key) { array[j + 1] = array[j]; int low = 0, high = array.length - 1; j--; while (low