w3resource

Numpy - Sort elements of a large array using For loop and Optimization

NumPy: Performance Optimization Exercise-15 with Solution

Write a NumPy program that creates a large NumPy array and write a function to sort its elements using a for loop. Optimize it using NumPy's sort() function.

Sample Solution:

Python Code:

import numpy as np

# Generate a large 1D NumPy array with random integers
large_array = np.random.randint(1, 10000, size=10000)

# Function to sort the array using a for loop (bubble sort for simplicity)
def sort_with_loop(arr):
    arr_copy = arr.copy()
    n = len(arr_copy)
    for i in range(n):
        for j in range(0, n-i-1):
            if arr_copy[j] > arr_copy[j+1]:
                arr_copy[j], arr_copy[j+1] = arr_copy[j+1], arr_copy[j]
    return arr_copy

# Sort the array using the for loop method
sorted_with_loop = sort_with_loop(large_array)

# Sort the array using NumPy's built-in sort() function
sorted_with_numpy = np.sort(large_array)

# Display first 10 sorted elements to verify
print("First 10 sorted elements using for loop:")
print(sorted_with_loop[:10])

print("First 10 sorted elements using NumPy:")
print(sorted_with_numpy[:10])

Output:

First 10 sorted elements using for loop:
[ 1  1  1  2  2  3  6 10 10 10]
First 10 sorted elements using NumPy:
[ 1  1  1  2  2  3  6 10 10 10]

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Generating a large array: A large 1D NumPy array with random integers is generated.
  • Defining the function: A function sort_with_loop is defined to sort the array using a for loop (bubble sort is used for simplicity).
  • Sorting with loop: The array is sorted using the for loop method.
  • Sorting with numpy: The array is sorted using NumPy's built-in sort() function.
  • Displaying results: The first 10 sorted elements from both methods are printed out to verify correctness.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Numpy - Compute column-wise Mean of large 2D array using For loop and Optimization.
Next: Numpy - Calculate outer product of two large arrays using For loops and Optimization.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/numpy-sort-elements-of-a-large-array-using-for-loop-and-optimization.php