# How to sort only the first k elements of an array using sort method?

**URL:** <https://verificationacademy.com/forums/t/how-to-sort-only-the-first-k-elements-of-an-array-using-sort-method/35370>\
**Category:** SystemVerilog\
**Tags:** packed-array-and-queues, SystemVerilog, systemverilog-Arrays-logics\
**Created:** [November 22, 2018, 5:58pm UTC](https://verificationacademy.com/forums/t/how-to-sort-only-the-first-k-elements-of-an-array-using-sort-method/35370 "2018-11-22T17:58:02Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![prabhakaran.gunasekaran](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/p/6bbea6/32.png) [@prabhakaran.gunasekaran](https://verificationacademy.com/forums/u/prabhakaran.gunasekaran)\
**Post date:** [November 23, 2018, 5:44am UTC](https://verificationacademy.com/forums/t/how-to-sort-only-the-first-k-elements-of-an-array-using-sort-method/35370/2 "2018-11-23T05:44:56Z")

</div>

_In reply to [Manoj J](https://verificationacademy.com/forums/t/how-to-sort-only-the-first-k-elements-of-an-array-using-sort-method/35370):_

```verilog

module tb();
  int q[$]={32'd11,32'd2,32'd13,32'd4,32'd15,32'd6,32'd17,32'd8,32'd19,32'd10};
  int a[$];
  int k;

initial begin
  k = 5;
  q.shuffle();
  for(int i=0;i<k;i++) a[i] = q[i];
  foreach(a[ii]) $display("before a[%0d] is : ",ii,a[ii]);
  a.sort();
  foreach(a[ii]) $display("after a[%0d] is : ",ii,a[ii]);
end
endmodule

```

---

_[View the full topic](https://verificationacademy.com/forums/t/how-to-sort-only-the-first-k-elements-of-an-array-using-sort-method/35370)._
