検索
ホームページJava&#&チュートリアルJava での回転ソート配列検索の構築: ピボット検索とバイナリ検索について

Building a Rotated Sorted Array Search in Java: Understanding Pivot and Binary Search

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:

  1. Find the Pivot: The pivot is the point where the array transitions from larger to smaller values.
  2. 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!

以上がJava での回転ソート配列検索の構築: ピボット検索とバイナリ検索についての詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Javaのプラットフォームの独立性を脅かしたり強化したりする新しいテクノロジーはありますか?Javaのプラットフォームの独立性を脅かしたり強化したりする新しいテクノロジーはありますか?Apr 24, 2025 am 12:11 AM

新しいテクノロジーは、両方の脅威をもたらし、Javaのプラットフォームの独立性を高めます。 1)Dockerなどのクラウドコンピューティングとコンテナ化テクノロジーは、Javaのプラットフォームの独立性を強化しますが、さまざまなクラウド環境に適応するために最適化する必要があります。 2)WebAssemblyは、Graalvmを介してJavaコードをコンパイルし、プラットフォームの独立性を拡張しますが、パフォーマンスのために他の言語と競合する必要があります。

JVMのさまざまな実装は何ですか、そしてそれらはすべて同じレベルのプラットフォームの独立性を提供しますか?JVMのさまざまな実装は何ですか、そしてそれらはすべて同じレベルのプラットフォームの独立性を提供しますか?Apr 24, 2025 am 12:10 AM

JVMの実装が異なると、プラットフォームの独立性が得られますが、パフォーマンスはわずかに異なります。 1。OracleHotspotとOpenJDKJVMは、プラットフォームの独立性で同様に機能しますが、OpenJDKは追加の構成が必要になる場合があります。 2。IBMJ9JVMは、特定のオペレーティングシステムで最適化を実行します。 3. Graalvmは複数の言語をサポートし、追加の構成が必要です。 4。AzulzingJVMには、特定のプラットフォーム調整が必要です。

プラットフォームの独立性は、開発コストと時間をどのように削減しますか?プラットフォームの独立性は、開発コストと時間をどのように削減しますか?Apr 24, 2025 am 12:08 AM

プラットフォームの独立性により、開発コストが削減され、複数のオペレーティングシステムで同じコードセットを実行することで開発時間を短縮します。具体的には、次のように表示されます。1。開発時間を短縮すると、1セットのコードのみが必要です。 2。メンテナンスコストを削減し、テストプロセスを統合します。 3.展開プロセスを簡素化するための迅速な反復とチームコラボレーション。

Javaのプラットフォームの独立性は、コードの再利用をどのように促進しますか?Javaのプラットフォームの独立性は、コードの再利用をどのように促進しますか?Apr 24, 2025 am 12:05 AM

java'splatformentedencefacilitatesecodereusebyAllowingbyTeCodeCodeCodeCodeTorunonAnyPlatformm.1)DevelopersConcodeCodeOnceOnceOnconconsentEntentEntEntEntEntEntentPlatforms.2)維持化されたアスカデドは、NoeedReadedoesではありません

Javaアプリケーションのプラットフォーム固有の問題をどのようにトラブルシューティングしますか?Javaアプリケーションのプラットフォーム固有の問題をどのようにトラブルシューティングしますか?Apr 24, 2025 am 12:04 AM

Javaアプリケーションのプラットフォーム固有の問題を解決するには、次の手順を実行できます。1。Javaのシステムクラスを使用して、システムプロパティを表示して実行中の環境を理解します。 2。ファイルクラスまたはjava.nio.fileパッケージを使用して、ファイルパスを処理します。 3。オペレーティングシステムの条件に応じてローカルライブラリをロードします。 4. VisualVMまたはJProfilerを使用して、クロスプラットフォームのパフォーマンスを最適化します。 5.テスト環境が、Dockerコンテナ化を通じて生産環境と一致していることを確認してください。 6. githubactionsを使用して、複数のプラットフォームで自動テストを実行します。これらの方法は、Javaアプリケーションでプラットフォーム固有の問題を効果的に解決するのに役立ちます。

JVMのクラスローダーサブシステムは、プラットフォームの独立性にどのように貢献していますか?JVMのクラスローダーサブシステムは、プラットフォームの独立性にどのように貢献していますか?Apr 23, 2025 am 12:14 AM

クラスローダーは、統一されたクラスファイル形式、動的読み込み、親代表団モデル、プラットフォーム非依存バイトコードを通じて、さまざまなプラットフォーム上のJavaプログラムの一貫性と互換性を保証し、プラットフォームの独立性を実現します。

Javaコンパイラはプラットフォーム固有のコードを作成しますか?説明する。Javaコンパイラはプラットフォーム固有のコードを作成しますか?説明する。Apr 23, 2025 am 12:09 AM

Javaコンパイラによって生成されたコードはプラットフォームに依存しませんが、最終的に実行されるコードはプラットフォーム固有です。 1。Javaソースコードは、プラットフォームに依存しないバイトコードにコンパイルされます。 2。JVMは、特定のプラットフォームのバイトコードをマシンコードに変換し、クロスプラットフォーム操作を保証しますが、パフォーマンスは異なる場合があります。

JVMは、さまざまなオペレーティングシステムでマルチスレッドをどのように処理しますか?JVMは、さまざまなオペレーティングシステムでマルチスレッドをどのように処理しますか?Apr 23, 2025 am 12:07 AM

マルチスレッドは、プログラムの応答性とリソースの利用を改善し、複雑な同時タスクを処理できるため、最新のプログラミングで重要です。 JVMは、スレッドマッピング、スケジューリングメカニズム、同期ロックメカニズムを介して、異なるオペレーティングシステム上のマルチスレッドの一貫性と効率を保証します。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

mPDF

mPDF

mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境