


What is a Rotated Sorted Array?
Consider a sorted array, for example:
[1, 2, 3, 4, 5, 6]
Now, if this array is rotated at some pivot, say at index 3, it would become:
[4, 5, 6, 1, 2, 3]
Notice that the array is still sorted, but it is divided into two parts. Our goal is to search for a target value in such arrays efficiently.
The Search Strategy
To search in a rotated sorted array, we need to:
- Find the Pivot: The pivot is the point where the array transitions from larger to smaller values.
- Binary Search: Once we find the pivot, we can use binary search on the appropriate half of the array.
Step-by-Step Code Explanation
class Solution { public static void main(String[] args) { int[] arr = {4, 5, 6, 1, 2, 3}; // Example of rotated sorted array int target = 5; // Searching for the target int result = search(arr, target); // Displaying the result System.out.println("Index of target: " + result); } // Main search function to find the target in a rotated sorted array public static int search(int[] nums, int target) { // Step 1: Find the pivot int pivot = searchPivot(nums); // Step 2: If no pivot, perform regular binary search if (pivot == -1) { return binarySearch(nums, target, 0, nums.length - 1); } // Step 3: If the target is at the pivot, return the pivot index if (nums[pivot] == target) { return pivot; } // Step 4: Decide which half of the array to search if (target >= nums[0]) { return binarySearch(nums, target, 0, pivot - 1); // Search left side } else { return binarySearch(nums, target, pivot + 1, nums.length - 1); // Search right side } } // Binary search helper function static int binarySearch(int[] arr, int target, int start, int end) { while (start arr[mid + 1]) { return mid; } // Check if the pivot is before the mid if (mid > start && arr[mid] <hr> <h3> Explanation of the Code </h3> <ol> <li> <p><strong>search()</strong>:</p> <ul> <li>This function is responsible for searching for the target in the rotated sorted array.</li> <li>First, we find the <strong>pivot</strong> using the searchPivot() function.</li> <li>Depending on the pivot's position, we then decide which half of the array to search using binary search.</li> </ul> </li> <li> <p><strong>binarySearch()</strong>:</p> <ul> <li>A standard binary search algorithm to find the target in a sorted sub-array.</li> <li>We define the start and end indices and progressively narrow the search space.</li> </ul> </li> <li> <p><strong>searchPivot()</strong>:</p> <ul> <li>This function identifies the pivot point (the place where the array rotates).</li> <li>The pivot is the index where the sorted order is "broken" (i.e., the array goes from a higher value to a lower value).</li> <li>If no pivot is found, it means the array was not rotated, and we can perform a regular binary search.</li> </ul> </li> </ol> <hr> <h3> How the Algorithm Works </h3> <p>For an array like [4, 5, 6, 1, 2, 3]:</p>
- The pivot is at index 2 (6 is the largest, and it is followed by 1, the smallest).
- We use this pivot to divide the array into two parts: [4, 5, 6] and [1, 2, 3].
- If the target is greater than or equal to the first element (4 in this case), we search the left half. Otherwise, we search the right half.
This method ensures that we search efficiently, achieving a time complexity of O(log n), similar to a standard binary search.
Conclusion
Rotated sorted arrays are a common interview question and a useful challenge to deepen your understanding of binary search. By finding the pivot and adapting our binary search accordingly, we can efficiently search through the array in logarithmic time.
If you found this article helpful, feel free to connect with me on LinkedIn or share your thoughts in the comments! Happy coding!
Das obige ist der detaillierte Inhalt vonErstellen einer rotierten sortierten Array-Suche in Java: Grundlegendes zur Pivot- und Binärsuche. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

In dem Artikel werden Maven und Gradle für Java -Projektmanagement, Aufbau von Automatisierung und Abhängigkeitslösung erörtert, die ihre Ansätze und Optimierungsstrategien vergleichen.

In dem Artikel werden benutzerdefinierte Java -Bibliotheken (JAR -Dateien) mit ordnungsgemäßem Versioning- und Abhängigkeitsmanagement erstellt und verwendet, wobei Tools wie Maven und Gradle verwendet werden.

In dem Artikel wird in der Implementierung von mehrstufigem Caching in Java mithilfe von Koffein- und Guava-Cache zur Verbesserung der Anwendungsleistung erläutert. Es deckt die Einrichtungs-, Integrations- und Leistungsvorteile sowie die Bestrafung des Konfigurations- und Räumungsrichtlinienmanagements ab

In dem Artikel werden mit JPA für Objektrelationszuordnungen mit erweiterten Funktionen wie Caching und faulen Laden erläutert. Es deckt Setup, Entity -Mapping und Best Practices zur Optimierung der Leistung ab und hebt potenzielle Fallstricke hervor. [159 Charaktere]

Mit der Klassenbelastung von Java wird das Laden, Verknüpfen und Initialisieren von Klassen mithilfe eines hierarchischen Systems mit Bootstrap-, Erweiterungs- und Anwendungsklassenloadern umfasst. Das übergeordnete Delegationsmodell stellt sicher


Heiße KI -Werkzeuge

Undresser.AI Undress
KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover
Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool
Ausziehbilder kostenlos

Clothoff.io
KI-Kleiderentferner

AI Hentai Generator
Erstellen Sie kostenlos Ai Hentai.

Heißer Artikel

Heiße Werkzeuge

Notepad++7.3.1
Einfach zu bedienender und kostenloser Code-Editor

Herunterladen der Mac-Version des Atom-Editors
Der beliebteste Open-Source-Editor

SAP NetWeaver Server-Adapter für Eclipse
Integrieren Sie Eclipse mit dem SAP NetWeaver-Anwendungsserver.

SecLists
SecLists ist der ultimative Begleiter für Sicherheitstester. Dabei handelt es sich um eine Sammlung verschiedener Arten von Listen, die häufig bei Sicherheitsbewertungen verwendet werden, an einem Ort. SecLists trägt dazu bei, Sicherheitstests effizienter und produktiver zu gestalten, indem es bequem alle Listen bereitstellt, die ein Sicherheitstester benötigen könnte. Zu den Listentypen gehören Benutzernamen, Passwörter, URLs, Fuzzing-Payloads, Muster für vertrauliche Daten, Web-Shells und mehr. Der Tester kann dieses Repository einfach auf einen neuen Testcomputer übertragen und hat dann Zugriff auf alle Arten von Listen, die er benötigt.

VSCode Windows 64-Bit-Download
Ein kostenloser und leistungsstarker IDE-Editor von Microsoft